php - How to always load a specific product attribute in Magento 2
Get the solution ↓↓↓I've extended the\Magento\Catalog\Model\Product
class, and added a new method that needs the value of a specific attribute.
However, this attribute is (usually) not available for thegetData()
method, because it isn't loaded.
Example:
class Product extends \Magento\Catalog\Model\Product
{
function isFoo()
{
// The following almost always returns false,
// because "my_attribute" is not loaded:
return $this->getData('my_attribute') == 'bar';
}
}
How do I tell Magento to always load this particular attribute, whenever it loads a product?
I don't care whether it comes from a collection, a repository, aload()
, or anything else, because I need to be able to call this method from everywhere (product listing, product page, shopping cart, ...).
I've tried using$this->load($this->getId());
in my method (ugly, I know), but it doesn't even work, because I end up with the following error message in a (seemingly) unrelated method:
Maximum function nesting level of '256' reached, aborting!
(The code is actually a bit more complex than shown, but callingload()
here was clearly wrong anyway).
I've also tried adding my attribute to acatalog_attributes.xml
file in theetc
folder of myCatalog
module, but it doesn't appear to do anything.
Answer
Solution:
So far, I've done 2 things:
Marked the attribute as Visible on Catalog Pages on Storefront and Used in Product Listing.
This can be done in a DataPatch or UpgradeData class:
$eavSetup->updateAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'my_attribute',
[
'used_in_product_listing' => true,
'is_visible_on_front' => true,
]
);
Overriden the Product Collection class:
class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection
{
/**
* {@inheritDoc}
*/
protected function _initSelect()
{
parent::_initSelect();
$this->addAttributeToSelect('my_attribute');
return $this;
}
}
The attribute now seems to be loaded when I try to use it. More testing is required, though.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot set properties of undefined (setting '_dt_cellindex')
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.