Magento2 – How to Get Product Attribute in Cart

attributesmagento2theme

I'm trying to grab a product attribute in the cart template. But I just does not work! The attribute is set to Visible on Catalog Pages on Storefront = yes and Used in Product Listing = yes

I use a custom module to override the following template:

/vendor/magento/module-checkout/view/frontend/templates/cart/item/default.phtml

I have the product:

$_item = $block->getItem();
$product = $_item->getProduct();

Normally I would expect a custom attribute (of type text-area in this case) with an attribute code of 'sample_attr' to be available with one of these:

$product->getData('sample_attr');

or

$product->getSampleAttr();

Some attributes are available using this (sku, weight, price ..), but for a custom attribute neither works.
The included helper (\Magento\Msrp\Helper\Data) also has no attribute method.

I can get all attribute codes using:

   $attributes = $product->getAttributes();
   foreach($attributes as $a)
   {
     var_dump($a->getName());
   }

I've also tried:

    $attribute = $product->getResource()->getAttribute('sample_attr');
    var_dump($attribute->getFrontend()->getValue($product));

but this returns null.

So how do I get the value of the attribute?

I've tried these:
Get specific attribute for each product on catalog page

Output custom text attribute in catalog list.phtml (Magento 2)

Best Answer

There is no necessity to change any PHP code for doing this.

You just need to create {MODULE_NAME}/etc/catalog_attributes.xml with such content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
    <group name="quote_item">
        <attribute name="sample_attr"/>
    </group>
</config>