I am trying to change the product name in the quote item via the event observer.
I followed this guide but it does not work.
public function execute(\Magento\Framework\Event\Observer $observer)
{
$item = $observer->getEvent()->getQuoteItem();
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->setName('New Name');
$item->getProduct()->setIsSuperMode(true);
}
The Event:
app/code/Test/Module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_product_add_after">
<observer name="dome_cart" instance="Test\Module\Observer\Option\AddCustomdOptionsToCart"/>
</event>
</config>
Best Answer
Magento 2 set quote item name from
Magento\Quote\Model\Quote\Item:setProduct
.And the name set by your observer class is overridden by
setProduct
.If you want to set your desire name for quote item then you have to
use after plugin on
Magento\Quote\Model\Quote\Item:setProduct
.Or use observer on event
sales_quote_item_set_product
.Using Plugin
Create di.xml at
app/code/{Vendor}/{ModuleName}/etc/
and defined plugin.And code
## Declare the plugin class
Item.php
atapp\code\{Vendor}\{ModuleName}\Plugin\Quote\Model\Quote
.And code:
Using Event & Observer Class
Defined an observer class
QuoteItemSetProduct.php
on the eventsales_quote_item_set_product
fromapp/code/{Vendor}/{ModuleName}/etc/events.xml
.Observer Class