Magento 2 – Change Product Name in Quote Item via Event Observer

event-observermagento2

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

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

<type name="Magento\Quote\Model\Quote\Item">
    <plugin disabled="false" name="StackExchange_Magento_Plugin_Magento_Quote_Model_Quote_Item" 
            sortOrder="10" type="{Vendor}\{ModuleName}\Plugin\Quote\Model\Quote\Item"/>
</type>

</config>

## Declare the plugin class Item.php at app\code\{Vendor}\{ModuleName}\Plugin\Quote\Model\Quote.

And code:

<?php
namespace {Vendor}\{ModuleName}\Plugin\Quote\Model\Quote;

class Item 
{
    public function afterSetProduct(
        \Magento\Quote\Model\Quote\Item $subject,
        $result
    ){
        $subject->setName('New Name');
    }
}

Using Event & Observer Class

Defined an observer class QuoteItemSetProduct.php on the event sales_quote_item_set_product from app/code/{Vendor}/{ModuleName}/etc/events.xml.

Observer Class

<?php
namespace {Vendor}\{ModuleName}\Observer\Sales;

class QuoteItemSetProduct implements \Magento\Framework\Event\ObserverInterface
{

    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {
    $quoteItem = $observer->getEvent()->getData('quote_item');
        $quoteItem->setName('New Name');
    }
}