0

I am trying to get the product attributes using the below 2 ways from the checkout cart model code but it is not working.

public function beforeAddProduct($subject, $productInfo, $requestInfo = null)
{
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/custom.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    
    // First Way to get attribute value
    
    // get quote items collection
    $itemsCollection = $this->cart->getQuote()->getItemsCollection();   
    foreach($itemsCollection as $item){
        
        // Below two lines not returning attribute value
        $logger->info($item->getAttribute('country_of_manufacture'));
        $logger->info($item->getProduct()->getCountryOfManufacture());
    }
    
    // Second Way to get attribute value
    
    // get quote items array
    $items = $this->cart->getQuote()->getAllItems();    
    foreach($items as $item) {          
        
       // Below three lines not returning attribute value
        $country_of_manufacture  = $item->getCountryOfManufacture();
        $country_of_manufacture = $item->getProduct()->getAttribute('country_of_manufacture');
        $country_of_manufacture = $item->getProduct()->getData('country_of_manufacture');
        
        $logger->info('Country: '.$country_of_manufacture); 
    }
    
    return [$productInfo, $requestInfo];

}

1 Answer 1

3

There is a new concept in Magento 2 to create a catalog_attributes.xml file in which you can define your custom attribute value using the quote_item group section

You Just need to create app/code/Vendor/Modulename/etc/catalog_attributes.xml with below 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="country_of_manufacture"/>
    </group>
</config>

you can get custom_attribute_name in the template file withcart/item/default.phtml below code.

<?= $_item->getProduct()->getData('custom_attribute_name');?>

Refresh the Cache and that’s it.

3
  • Thank you it is working, how to get the value of a select field <?= $_item->getProduct()->getData('country_of_manufacture');?> returns value not actual text.
    – ishaq
    Feb 16, 2022 at 4:41
  • I got it using $item->getProduct()->getAttributeText('country_of_manufacture')
    – ishaq
    Feb 16, 2022 at 4:57
  • its working code then give an upvote for this answer Feb 16, 2022 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.