Magento 2 - Set custom attribute value on cart page
No need to create any Observe, you can get it by simple below code.
Just need to create {MODULE_NAME}/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="custom_attribute"/>
</group>
</config>
You can get custome attribute in /templates/cart/item/default.phtml
with below code.
echo $_item->getProduct()->getData('custom_attribute');
In Magento 2
Change the following code:
Namespace/Modulename/Observer/salesQuoteItemSetCustomAttribute.php
<?php
namespace Namespace\Modulename\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Model\Product;
use Magento\Checkout\Model\Cart;
class salesQuoteItemSetCustomAttribute implements ObserverInterface
{
protected $_objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
\Magento\Framework\ObjectManagerInterface $interface,
\Magento\Quote\Model\Quote\Item $quote,
\CollectionFactory $productCollectionFactory
) {
$this->_objectManager = $objectManager;
$this->cart = $cart;
$this->product = $product;
$this->objectManager = $interface;
$this->quote = $quote;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$product = $observer->getProduct();
$quoteItem = $observer->getQuoteItem();
$quoteItem->setCustomAttribute($product->getCustomAttribute());
}
}
etc/events.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
<event name="sales_quote_item_set_product">
<observer
name="product_point_quote"
instance="Namespace\Modulename\Observer\salesQuoteItemSetCustomAttribute"/>
</event>
</config>
Create catalog_attributes.xml
in etc
to convert attribute to quote
:
<?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="custom_attribute"/>
</group>
</config>
This will bring your attribute on Cart Page