Magento 2: How to get current product name in an observer?Magento add custom options to cartHow can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlcatalog_product_load_before event gives getRequestedRouteName() errorGet current store name in observer methodmain.CRITICAL: Plugin class doesn't existSet custom price of product when adding to cart code not workingMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom Options

Why should universal income be universal?

Giving feedback to someone without sounding prejudiced

Is there a nicer/politer/more positive alternative for "negates"?

Is there a RAID 0 Equivalent for RAM?

Why does this expression simplify as such?

A variation to the phrase "hanging over my shoulders"

I found an audio circuit and I built it just fine, but I find it a bit too quiet. How do I amplify the output so that it is a bit louder?

Is this toilet slogan correct usage of the English language?

How to draw a matrix with arrows in limited space

Strong empirical falsification of quantum mechanics based on vacuum energy density?

15% tax on $7.5k earnings. Is that right?

Were Persian-Median kings illiterate?

Can I turn my anal-retentiveness into a career?

What kind of floor tile is this?

What fields between the rationals and the reals allow a good notion of 2D distance?

Why do Radio Buttons not fill the entire outer circle?

What is Cash Advance APR?

How to explain what's wrong with this application of the chain rule?

How does electrical safety system work on ISS?

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

How much of a Devil Fruit must be consumed to gain the power?

How can I write humor as character trait?

Pre-mixing cryogenic fuels and using only one fuel tank

Does "he squandered his car on drink" sound natural?



Magento 2: How to get current product name in an observer?


Magento add custom options to cartHow can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlcatalog_product_load_before event gives getRequestedRouteName() errorGet current store name in observer methodmain.CRITICAL: Plugin class doesn't existSet custom price of product when adding to cart code not workingMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom Options













0















I am using following observer in event.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_save_after">
<observer name="vendor_module_checkout_cart_save_after" instance="VendorModuleObserverCheckoutCartSaveAfterObserver" />
</event>
</config>


and here is my observer:



public function execute(EventObserver $observer)

$product = $observer->getEvent()->getProduct();
echo "proname: ".$product->getName();die;



but I am recieving following error:



Uncaught Error: Call to a member function getName() on null



Can anybody tell me how to get current product information using above observer?










share|improve this question




























    0















    I am using following observer in event.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_save_after">
    <observer name="vendor_module_checkout_cart_save_after" instance="VendorModuleObserverCheckoutCartSaveAfterObserver" />
    </event>
    </config>


    and here is my observer:



    public function execute(EventObserver $observer)

    $product = $observer->getEvent()->getProduct();
    echo "proname: ".$product->getName();die;



    but I am recieving following error:



    Uncaught Error: Call to a member function getName() on null



    Can anybody tell me how to get current product information using above observer?










    share|improve this question


























      0












      0








      0


      1






      I am using following observer in event.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_save_after">
      <observer name="vendor_module_checkout_cart_save_after" instance="VendorModuleObserverCheckoutCartSaveAfterObserver" />
      </event>
      </config>


      and here is my observer:



      public function execute(EventObserver $observer)

      $product = $observer->getEvent()->getProduct();
      echo "proname: ".$product->getName();die;



      but I am recieving following error:



      Uncaught Error: Call to a member function getName() on null



      Can anybody tell me how to get current product information using above observer?










      share|improve this question
















      I am using following observer in event.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_save_after">
      <observer name="vendor_module_checkout_cart_save_after" instance="VendorModuleObserverCheckoutCartSaveAfterObserver" />
      </event>
      </config>


      and here is my observer:



      public function execute(EventObserver $observer)

      $product = $observer->getEvent()->getProduct();
      echo "proname: ".$product->getName();die;



      but I am recieving following error:



      Uncaught Error: Call to a member function getName() on null



      Can anybody tell me how to get current product information using above observer?







      magento2 event-observer






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 30 '17 at 10:22







      Arshad Hussain

















      asked Nov 30 '17 at 10:17









      Arshad HussainArshad Hussain

      3731726




      3731726




















          6 Answers
          6






          active

          oldest

          votes


















          2














          1.oneway:



          public function execute(MagentoFrameworkEventObserver $observer)

          //Product get product name
          $observer->getProduct()->getName();



          2.Registry:



          $this->product = $this->registry->registry('product');
          $this->product->getName();





          share|improve this answer
































            1














            You can use GetQuoteItem ojbect from observer and check as below,



            public function execute(EventObserver $observer)

            $product = $observer->getQuoteItem();
            echo "product Id: ".$product->getId();die;






            share|improve this answer























            • getting same error: Uncaught Error: Call to a member function getId() on null

              – Arshad Hussain
              Nov 30 '17 at 10:35











            • Could you replace your event with checkout_cart_product_add_after and check

              – Rakesh Jesadiya
              Nov 30 '17 at 10:38











            • I can replace but for some reason I am using that observer and I want that observer anyhow.

              – Arshad Hussain
              Nov 30 '17 at 10:39


















            1














            First you this event is only object of MagentoCheckoutModelCart as a paramter




            $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' =>
            $this]);




            So, you can only call of this class public functions getItems().



            In class this, has a function which give you current cart all object.So using this function get all items details.



             public function execute(EventObserver $observer)

            $cart = $observer->getCart();
            $allitems = $cart->getItems();
            /* get allitems */
            $lastItem =[];
            if(!empty($allitems))

            foreach ($allitems as $item)

            / * add this */
            if ($item->getParentItemId())
            continue;

            $lastItem[$item->getId()] = $item;

            // last add item
            $lastestItem = max($lastItem);
            $lastestItem->getProduct()->getName();
            $lastestItem->getProduct()->getPrice();








            share|improve this answer

























            • is it possible to get only current added item in cart. I donot want to get all items in cart. I only want item that I have added in cart currently.

              – Arshad Hussain
              Nov 30 '17 at 11:36











            • Suggest to use event: checkout_cart_add_product_complete and which $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] );

              – Amit Bera
              Nov 30 '17 at 11:41











            • This event will not give any information of quote item.

              – Arshad Hussain
              Nov 30 '17 at 11:47


















            0














            Try to use this code :



            $product = $observer->getEvent()->getData('product');
            $productId = $product->getId();





            share|improve this answer























            • getting same error: Uncaught Error: Call to a member function getId() on null

              – Arshad Hussain
              Nov 30 '17 at 10:27


















            0














            The best way to know which data you can to use is go to the place where the event is dispatched. So just search by name of event (in your way checkout_cart_save_after). After that you rich this method in Cart Model:



             /**
            * Save cart
            *
            * @return $this
            */
            public function save()

            $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);

            $this->getQuote()->getBillingAddress();
            $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
            $this->getQuote()->collectTotals();
            $this->quoteRepository->save($this->getQuote());
            $this->_checkoutSession->setQuoteId($this->getQuote()->getId());
            /**
            * Cart save usually called after changes with cart items.
            */
            $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
            $this->reinitializeState();
            return $this;



            As you can see you have data item "cart" that contains this model object. So get it in your observer:



            public function execute(Observer $observer)

            /** @var MagentoCheckoutModelCart $cart */
            $cart = $observer->getData('cart');



            After that you will have the cart model and it allows to use any methods of this model. In your way you need products in the cart. For get it use the method $productIds = $cart->getQuoteProductIds(). Then if you need to load Product data you should load the product models by Products IDs through ProductRepository. Add to you __construct dependency injection:



             /**
            * @var MagentoCatalogApiProductRepositoryInterface
            */
            protected $productRepository;

            /**
            * CheckoutCartSaveAfter constructor.
            *
            * @param MagentoCatalogApiProductRepositoryInterface $productRepository
            */
            public function __construct(ProductRepositoryInterface $productRepository)

            $this->productRepository = $productRepository;



            For sure don't forgot to use this commands after that:



            php bin/magento setup:upgrade && php bin/magento setup:di:compile


            Then loads product models and get a product name or whatever you want.



             /** @var MagentoCatalogModelProduct[] $products */
            $products = [];
            foreach ($productIds as $productId)
            $products[$productId] = $this->productRepository->getById($productId);


            foreach ($products as $product)
            var_dump($product->getName());



            Full example of observer is below:



            <?php

            namespace VendorModuleObserver;

            use MagentoCatalogApiProductRepositoryInterface;
            use MagentoFrameworkEventObserver;
            use MagentoFrameworkEventObserverInterface;

            class CheckoutCartSaveAfter implements ObserverInterface

            /**
            * @var MagentoCatalogApiProductRepositoryInterface
            */
            protected $productRepository;

            /**
            * CheckoutCartSaveAfter constructor.
            *
            * @param MagentoCatalogApiProductRepositoryInterface $productRepository
            */
            public function __construct(ProductRepositoryInterface $productRepository)

            $this->productRepository = $productRepository;


            /**
            * @inheritdoc
            */
            public function execute(Observer $observer)

            /** @var MagentoCheckoutModelCart $cart */
            $cart = $observer->getData('cart');

            $productIds = $cart->getQuoteProductIds();

            /** @var MagentoCatalogModelProduct[] $products */
            $products = [];
            foreach ($productIds as $productId)
            $products[$productId] = $this->productRepository->getById($productId);


            foreach ($products as $product)
            var_dump($product->getName());









            share|improve this answer
































              0














              You need create file inside appcodeVendorMyPackageObserverProductSaveafter.php



              <?php
              namespace VendoMyPackageObserver;
              use MagentoFrameworkEventObserverInterface;
              use MagentoFrameworkEventObserver as EventObserver;

              class ProductSaveAfter implements ObserverInterface
              {

              public function execute(MagentoFrameworkEventObserver $observer)

              /** @var MagentoCatalogModelProduct $product */
              $product = $observer->getEvent()->getProduct();
              $productID=$product->getId();
              var_dump($productID);
              die();



              Next another file appcodeVendorMyPackageetcadminhtmlevents.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="catalog_product_save_after">
              <observer name="save_example_data" instance="VendorMyPackageObserverProductSaveAfter" />
              </event>
              </config>





              share|improve this answer






















                Your Answer








                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "479"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f203904%2fmagento-2-how-to-get-current-product-name-in-an-observer%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                6 Answers
                6






                active

                oldest

                votes








                6 Answers
                6






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                2














                1.oneway:



                public function execute(MagentoFrameworkEventObserver $observer)

                //Product get product name
                $observer->getProduct()->getName();



                2.Registry:



                $this->product = $this->registry->registry('product');
                $this->product->getName();





                share|improve this answer





























                  2














                  1.oneway:



                  public function execute(MagentoFrameworkEventObserver $observer)

                  //Product get product name
                  $observer->getProduct()->getName();



                  2.Registry:



                  $this->product = $this->registry->registry('product');
                  $this->product->getName();





                  share|improve this answer



























                    2












                    2








                    2







                    1.oneway:



                    public function execute(MagentoFrameworkEventObserver $observer)

                    //Product get product name
                    $observer->getProduct()->getName();



                    2.Registry:



                    $this->product = $this->registry->registry('product');
                    $this->product->getName();





                    share|improve this answer















                    1.oneway:



                    public function execute(MagentoFrameworkEventObserver $observer)

                    //Product get product name
                    $observer->getProduct()->getName();



                    2.Registry:



                    $this->product = $this->registry->registry('product');
                    $this->product->getName();






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 30 '17 at 11:29

























                    answered Nov 30 '17 at 11:16









                    Pramod KharadePramod Kharade

                    1,7521028




                    1,7521028























                        1














                        You can use GetQuoteItem ojbect from observer and check as below,



                        public function execute(EventObserver $observer)

                        $product = $observer->getQuoteItem();
                        echo "product Id: ".$product->getId();die;






                        share|improve this answer























                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:35











                        • Could you replace your event with checkout_cart_product_add_after and check

                          – Rakesh Jesadiya
                          Nov 30 '17 at 10:38











                        • I can replace but for some reason I am using that observer and I want that observer anyhow.

                          – Arshad Hussain
                          Nov 30 '17 at 10:39















                        1














                        You can use GetQuoteItem ojbect from observer and check as below,



                        public function execute(EventObserver $observer)

                        $product = $observer->getQuoteItem();
                        echo "product Id: ".$product->getId();die;






                        share|improve this answer























                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:35











                        • Could you replace your event with checkout_cart_product_add_after and check

                          – Rakesh Jesadiya
                          Nov 30 '17 at 10:38











                        • I can replace but for some reason I am using that observer and I want that observer anyhow.

                          – Arshad Hussain
                          Nov 30 '17 at 10:39













                        1












                        1








                        1







                        You can use GetQuoteItem ojbect from observer and check as below,



                        public function execute(EventObserver $observer)

                        $product = $observer->getQuoteItem();
                        echo "product Id: ".$product->getId();die;






                        share|improve this answer













                        You can use GetQuoteItem ojbect from observer and check as below,



                        public function execute(EventObserver $observer)

                        $product = $observer->getQuoteItem();
                        echo "product Id: ".$product->getId();die;







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 30 '17 at 10:29









                        Rakesh JesadiyaRakesh Jesadiya

                        29.9k1576123




                        29.9k1576123












                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:35











                        • Could you replace your event with checkout_cart_product_add_after and check

                          – Rakesh Jesadiya
                          Nov 30 '17 at 10:38











                        • I can replace but for some reason I am using that observer and I want that observer anyhow.

                          – Arshad Hussain
                          Nov 30 '17 at 10:39

















                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:35











                        • Could you replace your event with checkout_cart_product_add_after and check

                          – Rakesh Jesadiya
                          Nov 30 '17 at 10:38











                        • I can replace but for some reason I am using that observer and I want that observer anyhow.

                          – Arshad Hussain
                          Nov 30 '17 at 10:39
















                        getting same error: Uncaught Error: Call to a member function getId() on null

                        – Arshad Hussain
                        Nov 30 '17 at 10:35





                        getting same error: Uncaught Error: Call to a member function getId() on null

                        – Arshad Hussain
                        Nov 30 '17 at 10:35













                        Could you replace your event with checkout_cart_product_add_after and check

                        – Rakesh Jesadiya
                        Nov 30 '17 at 10:38





                        Could you replace your event with checkout_cart_product_add_after and check

                        – Rakesh Jesadiya
                        Nov 30 '17 at 10:38













                        I can replace but for some reason I am using that observer and I want that observer anyhow.

                        – Arshad Hussain
                        Nov 30 '17 at 10:39





                        I can replace but for some reason I am using that observer and I want that observer anyhow.

                        – Arshad Hussain
                        Nov 30 '17 at 10:39











                        1














                        First you this event is only object of MagentoCheckoutModelCart as a paramter




                        $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' =>
                        $this]);




                        So, you can only call of this class public functions getItems().



                        In class this, has a function which give you current cart all object.So using this function get all items details.



                         public function execute(EventObserver $observer)

                        $cart = $observer->getCart();
                        $allitems = $cart->getItems();
                        /* get allitems */
                        $lastItem =[];
                        if(!empty($allitems))

                        foreach ($allitems as $item)

                        / * add this */
                        if ($item->getParentItemId())
                        continue;

                        $lastItem[$item->getId()] = $item;

                        // last add item
                        $lastestItem = max($lastItem);
                        $lastestItem->getProduct()->getName();
                        $lastestItem->getProduct()->getPrice();








                        share|improve this answer

























                        • is it possible to get only current added item in cart. I donot want to get all items in cart. I only want item that I have added in cart currently.

                          – Arshad Hussain
                          Nov 30 '17 at 11:36











                        • Suggest to use event: checkout_cart_add_product_complete and which $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] );

                          – Amit Bera
                          Nov 30 '17 at 11:41











                        • This event will not give any information of quote item.

                          – Arshad Hussain
                          Nov 30 '17 at 11:47















                        1














                        First you this event is only object of MagentoCheckoutModelCart as a paramter




                        $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' =>
                        $this]);




                        So, you can only call of this class public functions getItems().



                        In class this, has a function which give you current cart all object.So using this function get all items details.



                         public function execute(EventObserver $observer)

                        $cart = $observer->getCart();
                        $allitems = $cart->getItems();
                        /* get allitems */
                        $lastItem =[];
                        if(!empty($allitems))

                        foreach ($allitems as $item)

                        / * add this */
                        if ($item->getParentItemId())
                        continue;

                        $lastItem[$item->getId()] = $item;

                        // last add item
                        $lastestItem = max($lastItem);
                        $lastestItem->getProduct()->getName();
                        $lastestItem->getProduct()->getPrice();








                        share|improve this answer

























                        • is it possible to get only current added item in cart. I donot want to get all items in cart. I only want item that I have added in cart currently.

                          – Arshad Hussain
                          Nov 30 '17 at 11:36











                        • Suggest to use event: checkout_cart_add_product_complete and which $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] );

                          – Amit Bera
                          Nov 30 '17 at 11:41











                        • This event will not give any information of quote item.

                          – Arshad Hussain
                          Nov 30 '17 at 11:47













                        1












                        1








                        1







                        First you this event is only object of MagentoCheckoutModelCart as a paramter




                        $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' =>
                        $this]);




                        So, you can only call of this class public functions getItems().



                        In class this, has a function which give you current cart all object.So using this function get all items details.



                         public function execute(EventObserver $observer)

                        $cart = $observer->getCart();
                        $allitems = $cart->getItems();
                        /* get allitems */
                        $lastItem =[];
                        if(!empty($allitems))

                        foreach ($allitems as $item)

                        / * add this */
                        if ($item->getParentItemId())
                        continue;

                        $lastItem[$item->getId()] = $item;

                        // last add item
                        $lastestItem = max($lastItem);
                        $lastestItem->getProduct()->getName();
                        $lastestItem->getProduct()->getPrice();








                        share|improve this answer















                        First you this event is only object of MagentoCheckoutModelCart as a paramter




                        $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' =>
                        $this]);




                        So, you can only call of this class public functions getItems().



                        In class this, has a function which give you current cart all object.So using this function get all items details.



                         public function execute(EventObserver $observer)

                        $cart = $observer->getCart();
                        $allitems = $cart->getItems();
                        /* get allitems */
                        $lastItem =[];
                        if(!empty($allitems))

                        foreach ($allitems as $item)

                        / * add this */
                        if ($item->getParentItemId())
                        continue;

                        $lastItem[$item->getId()] = $item;

                        // last add item
                        $lastestItem = max($lastItem);
                        $lastestItem->getProduct()->getName();
                        $lastestItem->getProduct()->getPrice();









                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 30 '17 at 11:47

























                        answered Nov 30 '17 at 11:06









                        Amit BeraAmit Bera

                        59.3k1675177




                        59.3k1675177












                        • is it possible to get only current added item in cart. I donot want to get all items in cart. I only want item that I have added in cart currently.

                          – Arshad Hussain
                          Nov 30 '17 at 11:36











                        • Suggest to use event: checkout_cart_add_product_complete and which $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] );

                          – Amit Bera
                          Nov 30 '17 at 11:41











                        • This event will not give any information of quote item.

                          – Arshad Hussain
                          Nov 30 '17 at 11:47

















                        • is it possible to get only current added item in cart. I donot want to get all items in cart. I only want item that I have added in cart currently.

                          – Arshad Hussain
                          Nov 30 '17 at 11:36











                        • Suggest to use event: checkout_cart_add_product_complete and which $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] );

                          – Amit Bera
                          Nov 30 '17 at 11:41











                        • This event will not give any information of quote item.

                          – Arshad Hussain
                          Nov 30 '17 at 11:47
















                        is it possible to get only current added item in cart. I donot want to get all items in cart. I only want item that I have added in cart currently.

                        – Arshad Hussain
                        Nov 30 '17 at 11:36





                        is it possible to get only current added item in cart. I donot want to get all items in cart. I only want item that I have added in cart currently.

                        – Arshad Hussain
                        Nov 30 '17 at 11:36













                        Suggest to use event: checkout_cart_add_product_complete and which $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] );

                        – Amit Bera
                        Nov 30 '17 at 11:41





                        Suggest to use event: checkout_cart_add_product_complete and which $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] );

                        – Amit Bera
                        Nov 30 '17 at 11:41













                        This event will not give any information of quote item.

                        – Arshad Hussain
                        Nov 30 '17 at 11:47





                        This event will not give any information of quote item.

                        – Arshad Hussain
                        Nov 30 '17 at 11:47











                        0














                        Try to use this code :



                        $product = $observer->getEvent()->getData('product');
                        $productId = $product->getId();





                        share|improve this answer























                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:27















                        0














                        Try to use this code :



                        $product = $observer->getEvent()->getData('product');
                        $productId = $product->getId();





                        share|improve this answer























                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:27













                        0












                        0








                        0







                        Try to use this code :



                        $product = $observer->getEvent()->getData('product');
                        $productId = $product->getId();





                        share|improve this answer













                        Try to use this code :



                        $product = $observer->getEvent()->getData('product');
                        $productId = $product->getId();






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 30 '17 at 10:23









                        Rohan HapaniRohan Hapani

                        6,65331865




                        6,65331865












                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:27

















                        • getting same error: Uncaught Error: Call to a member function getId() on null

                          – Arshad Hussain
                          Nov 30 '17 at 10:27
















                        getting same error: Uncaught Error: Call to a member function getId() on null

                        – Arshad Hussain
                        Nov 30 '17 at 10:27





                        getting same error: Uncaught Error: Call to a member function getId() on null

                        – Arshad Hussain
                        Nov 30 '17 at 10:27











                        0














                        The best way to know which data you can to use is go to the place where the event is dispatched. So just search by name of event (in your way checkout_cart_save_after). After that you rich this method in Cart Model:



                         /**
                        * Save cart
                        *
                        * @return $this
                        */
                        public function save()

                        $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);

                        $this->getQuote()->getBillingAddress();
                        $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
                        $this->getQuote()->collectTotals();
                        $this->quoteRepository->save($this->getQuote());
                        $this->_checkoutSession->setQuoteId($this->getQuote()->getId());
                        /**
                        * Cart save usually called after changes with cart items.
                        */
                        $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
                        $this->reinitializeState();
                        return $this;



                        As you can see you have data item "cart" that contains this model object. So get it in your observer:



                        public function execute(Observer $observer)

                        /** @var MagentoCheckoutModelCart $cart */
                        $cart = $observer->getData('cart');



                        After that you will have the cart model and it allows to use any methods of this model. In your way you need products in the cart. For get it use the method $productIds = $cart->getQuoteProductIds(). Then if you need to load Product data you should load the product models by Products IDs through ProductRepository. Add to you __construct dependency injection:



                         /**
                        * @var MagentoCatalogApiProductRepositoryInterface
                        */
                        protected $productRepository;

                        /**
                        * CheckoutCartSaveAfter constructor.
                        *
                        * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                        */
                        public function __construct(ProductRepositoryInterface $productRepository)

                        $this->productRepository = $productRepository;



                        For sure don't forgot to use this commands after that:



                        php bin/magento setup:upgrade && php bin/magento setup:di:compile


                        Then loads product models and get a product name or whatever you want.



                         /** @var MagentoCatalogModelProduct[] $products */
                        $products = [];
                        foreach ($productIds as $productId)
                        $products[$productId] = $this->productRepository->getById($productId);


                        foreach ($products as $product)
                        var_dump($product->getName());



                        Full example of observer is below:



                        <?php

                        namespace VendorModuleObserver;

                        use MagentoCatalogApiProductRepositoryInterface;
                        use MagentoFrameworkEventObserver;
                        use MagentoFrameworkEventObserverInterface;

                        class CheckoutCartSaveAfter implements ObserverInterface

                        /**
                        * @var MagentoCatalogApiProductRepositoryInterface
                        */
                        protected $productRepository;

                        /**
                        * CheckoutCartSaveAfter constructor.
                        *
                        * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                        */
                        public function __construct(ProductRepositoryInterface $productRepository)

                        $this->productRepository = $productRepository;


                        /**
                        * @inheritdoc
                        */
                        public function execute(Observer $observer)

                        /** @var MagentoCheckoutModelCart $cart */
                        $cart = $observer->getData('cart');

                        $productIds = $cart->getQuoteProductIds();

                        /** @var MagentoCatalogModelProduct[] $products */
                        $products = [];
                        foreach ($productIds as $productId)
                        $products[$productId] = $this->productRepository->getById($productId);


                        foreach ($products as $product)
                        var_dump($product->getName());









                        share|improve this answer





























                          0














                          The best way to know which data you can to use is go to the place where the event is dispatched. So just search by name of event (in your way checkout_cart_save_after). After that you rich this method in Cart Model:



                           /**
                          * Save cart
                          *
                          * @return $this
                          */
                          public function save()

                          $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);

                          $this->getQuote()->getBillingAddress();
                          $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
                          $this->getQuote()->collectTotals();
                          $this->quoteRepository->save($this->getQuote());
                          $this->_checkoutSession->setQuoteId($this->getQuote()->getId());
                          /**
                          * Cart save usually called after changes with cart items.
                          */
                          $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
                          $this->reinitializeState();
                          return $this;



                          As you can see you have data item "cart" that contains this model object. So get it in your observer:



                          public function execute(Observer $observer)

                          /** @var MagentoCheckoutModelCart $cart */
                          $cart = $observer->getData('cart');



                          After that you will have the cart model and it allows to use any methods of this model. In your way you need products in the cart. For get it use the method $productIds = $cart->getQuoteProductIds(). Then if you need to load Product data you should load the product models by Products IDs through ProductRepository. Add to you __construct dependency injection:



                           /**
                          * @var MagentoCatalogApiProductRepositoryInterface
                          */
                          protected $productRepository;

                          /**
                          * CheckoutCartSaveAfter constructor.
                          *
                          * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                          */
                          public function __construct(ProductRepositoryInterface $productRepository)

                          $this->productRepository = $productRepository;



                          For sure don't forgot to use this commands after that:



                          php bin/magento setup:upgrade && php bin/magento setup:di:compile


                          Then loads product models and get a product name or whatever you want.



                           /** @var MagentoCatalogModelProduct[] $products */
                          $products = [];
                          foreach ($productIds as $productId)
                          $products[$productId] = $this->productRepository->getById($productId);


                          foreach ($products as $product)
                          var_dump($product->getName());



                          Full example of observer is below:



                          <?php

                          namespace VendorModuleObserver;

                          use MagentoCatalogApiProductRepositoryInterface;
                          use MagentoFrameworkEventObserver;
                          use MagentoFrameworkEventObserverInterface;

                          class CheckoutCartSaveAfter implements ObserverInterface

                          /**
                          * @var MagentoCatalogApiProductRepositoryInterface
                          */
                          protected $productRepository;

                          /**
                          * CheckoutCartSaveAfter constructor.
                          *
                          * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                          */
                          public function __construct(ProductRepositoryInterface $productRepository)

                          $this->productRepository = $productRepository;


                          /**
                          * @inheritdoc
                          */
                          public function execute(Observer $observer)

                          /** @var MagentoCheckoutModelCart $cart */
                          $cart = $observer->getData('cart');

                          $productIds = $cart->getQuoteProductIds();

                          /** @var MagentoCatalogModelProduct[] $products */
                          $products = [];
                          foreach ($productIds as $productId)
                          $products[$productId] = $this->productRepository->getById($productId);


                          foreach ($products as $product)
                          var_dump($product->getName());









                          share|improve this answer



























                            0












                            0








                            0







                            The best way to know which data you can to use is go to the place where the event is dispatched. So just search by name of event (in your way checkout_cart_save_after). After that you rich this method in Cart Model:



                             /**
                            * Save cart
                            *
                            * @return $this
                            */
                            public function save()

                            $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);

                            $this->getQuote()->getBillingAddress();
                            $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
                            $this->getQuote()->collectTotals();
                            $this->quoteRepository->save($this->getQuote());
                            $this->_checkoutSession->setQuoteId($this->getQuote()->getId());
                            /**
                            * Cart save usually called after changes with cart items.
                            */
                            $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
                            $this->reinitializeState();
                            return $this;



                            As you can see you have data item "cart" that contains this model object. So get it in your observer:



                            public function execute(Observer $observer)

                            /** @var MagentoCheckoutModelCart $cart */
                            $cart = $observer->getData('cart');



                            After that you will have the cart model and it allows to use any methods of this model. In your way you need products in the cart. For get it use the method $productIds = $cart->getQuoteProductIds(). Then if you need to load Product data you should load the product models by Products IDs through ProductRepository. Add to you __construct dependency injection:



                             /**
                            * @var MagentoCatalogApiProductRepositoryInterface
                            */
                            protected $productRepository;

                            /**
                            * CheckoutCartSaveAfter constructor.
                            *
                            * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                            */
                            public function __construct(ProductRepositoryInterface $productRepository)

                            $this->productRepository = $productRepository;



                            For sure don't forgot to use this commands after that:



                            php bin/magento setup:upgrade && php bin/magento setup:di:compile


                            Then loads product models and get a product name or whatever you want.



                             /** @var MagentoCatalogModelProduct[] $products */
                            $products = [];
                            foreach ($productIds as $productId)
                            $products[$productId] = $this->productRepository->getById($productId);


                            foreach ($products as $product)
                            var_dump($product->getName());



                            Full example of observer is below:



                            <?php

                            namespace VendorModuleObserver;

                            use MagentoCatalogApiProductRepositoryInterface;
                            use MagentoFrameworkEventObserver;
                            use MagentoFrameworkEventObserverInterface;

                            class CheckoutCartSaveAfter implements ObserverInterface

                            /**
                            * @var MagentoCatalogApiProductRepositoryInterface
                            */
                            protected $productRepository;

                            /**
                            * CheckoutCartSaveAfter constructor.
                            *
                            * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                            */
                            public function __construct(ProductRepositoryInterface $productRepository)

                            $this->productRepository = $productRepository;


                            /**
                            * @inheritdoc
                            */
                            public function execute(Observer $observer)

                            /** @var MagentoCheckoutModelCart $cart */
                            $cart = $observer->getData('cart');

                            $productIds = $cart->getQuoteProductIds();

                            /** @var MagentoCatalogModelProduct[] $products */
                            $products = [];
                            foreach ($productIds as $productId)
                            $products[$productId] = $this->productRepository->getById($productId);


                            foreach ($products as $product)
                            var_dump($product->getName());









                            share|improve this answer















                            The best way to know which data you can to use is go to the place where the event is dispatched. So just search by name of event (in your way checkout_cart_save_after). After that you rich this method in Cart Model:



                             /**
                            * Save cart
                            *
                            * @return $this
                            */
                            public function save()

                            $this->_eventManager->dispatch('checkout_cart_save_before', ['cart' => $this]);

                            $this->getQuote()->getBillingAddress();
                            $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
                            $this->getQuote()->collectTotals();
                            $this->quoteRepository->save($this->getQuote());
                            $this->_checkoutSession->setQuoteId($this->getQuote()->getId());
                            /**
                            * Cart save usually called after changes with cart items.
                            */
                            $this->_eventManager->dispatch('checkout_cart_save_after', ['cart' => $this]);
                            $this->reinitializeState();
                            return $this;



                            As you can see you have data item "cart" that contains this model object. So get it in your observer:



                            public function execute(Observer $observer)

                            /** @var MagentoCheckoutModelCart $cart */
                            $cart = $observer->getData('cart');



                            After that you will have the cart model and it allows to use any methods of this model. In your way you need products in the cart. For get it use the method $productIds = $cart->getQuoteProductIds(). Then if you need to load Product data you should load the product models by Products IDs through ProductRepository. Add to you __construct dependency injection:



                             /**
                            * @var MagentoCatalogApiProductRepositoryInterface
                            */
                            protected $productRepository;

                            /**
                            * CheckoutCartSaveAfter constructor.
                            *
                            * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                            */
                            public function __construct(ProductRepositoryInterface $productRepository)

                            $this->productRepository = $productRepository;



                            For sure don't forgot to use this commands after that:



                            php bin/magento setup:upgrade && php bin/magento setup:di:compile


                            Then loads product models and get a product name or whatever you want.



                             /** @var MagentoCatalogModelProduct[] $products */
                            $products = [];
                            foreach ($productIds as $productId)
                            $products[$productId] = $this->productRepository->getById($productId);


                            foreach ($products as $product)
                            var_dump($product->getName());



                            Full example of observer is below:



                            <?php

                            namespace VendorModuleObserver;

                            use MagentoCatalogApiProductRepositoryInterface;
                            use MagentoFrameworkEventObserver;
                            use MagentoFrameworkEventObserverInterface;

                            class CheckoutCartSaveAfter implements ObserverInterface

                            /**
                            * @var MagentoCatalogApiProductRepositoryInterface
                            */
                            protected $productRepository;

                            /**
                            * CheckoutCartSaveAfter constructor.
                            *
                            * @param MagentoCatalogApiProductRepositoryInterface $productRepository
                            */
                            public function __construct(ProductRepositoryInterface $productRepository)

                            $this->productRepository = $productRepository;


                            /**
                            * @inheritdoc
                            */
                            public function execute(Observer $observer)

                            /** @var MagentoCheckoutModelCart $cart */
                            $cart = $observer->getData('cart');

                            $productIds = $cart->getQuoteProductIds();

                            /** @var MagentoCatalogModelProduct[] $products */
                            $products = [];
                            foreach ($productIds as $productId)
                            $products[$productId] = $this->productRepository->getById($productId);


                            foreach ($products as $product)
                            var_dump($product->getName());










                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 30 '17 at 12:37

























                            answered Nov 30 '17 at 12:14









                            Dmitriy ChizhovDmitriy Chizhov

                            265




                            265





















                                0














                                You need create file inside appcodeVendorMyPackageObserverProductSaveafter.php



                                <?php
                                namespace VendoMyPackageObserver;
                                use MagentoFrameworkEventObserverInterface;
                                use MagentoFrameworkEventObserver as EventObserver;

                                class ProductSaveAfter implements ObserverInterface
                                {

                                public function execute(MagentoFrameworkEventObserver $observer)

                                /** @var MagentoCatalogModelProduct $product */
                                $product = $observer->getEvent()->getProduct();
                                $productID=$product->getId();
                                var_dump($productID);
                                die();



                                Next another file appcodeVendorMyPackageetcadminhtmlevents.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="catalog_product_save_after">
                                <observer name="save_example_data" instance="VendorMyPackageObserverProductSaveAfter" />
                                </event>
                                </config>





                                share|improve this answer



























                                  0














                                  You need create file inside appcodeVendorMyPackageObserverProductSaveafter.php



                                  <?php
                                  namespace VendoMyPackageObserver;
                                  use MagentoFrameworkEventObserverInterface;
                                  use MagentoFrameworkEventObserver as EventObserver;

                                  class ProductSaveAfter implements ObserverInterface
                                  {

                                  public function execute(MagentoFrameworkEventObserver $observer)

                                  /** @var MagentoCatalogModelProduct $product */
                                  $product = $observer->getEvent()->getProduct();
                                  $productID=$product->getId();
                                  var_dump($productID);
                                  die();



                                  Next another file appcodeVendorMyPackageetcadminhtmlevents.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="catalog_product_save_after">
                                  <observer name="save_example_data" instance="VendorMyPackageObserverProductSaveAfter" />
                                  </event>
                                  </config>





                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    You need create file inside appcodeVendorMyPackageObserverProductSaveafter.php



                                    <?php
                                    namespace VendoMyPackageObserver;
                                    use MagentoFrameworkEventObserverInterface;
                                    use MagentoFrameworkEventObserver as EventObserver;

                                    class ProductSaveAfter implements ObserverInterface
                                    {

                                    public function execute(MagentoFrameworkEventObserver $observer)

                                    /** @var MagentoCatalogModelProduct $product */
                                    $product = $observer->getEvent()->getProduct();
                                    $productID=$product->getId();
                                    var_dump($productID);
                                    die();



                                    Next another file appcodeVendorMyPackageetcadminhtmlevents.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="catalog_product_save_after">
                                    <observer name="save_example_data" instance="VendorMyPackageObserverProductSaveAfter" />
                                    </event>
                                    </config>





                                    share|improve this answer













                                    You need create file inside appcodeVendorMyPackageObserverProductSaveafter.php



                                    <?php
                                    namespace VendoMyPackageObserver;
                                    use MagentoFrameworkEventObserverInterface;
                                    use MagentoFrameworkEventObserver as EventObserver;

                                    class ProductSaveAfter implements ObserverInterface
                                    {

                                    public function execute(MagentoFrameworkEventObserver $observer)

                                    /** @var MagentoCatalogModelProduct $product */
                                    $product = $observer->getEvent()->getProduct();
                                    $productID=$product->getId();
                                    var_dump($productID);
                                    die();



                                    Next another file appcodeVendorMyPackageetcadminhtmlevents.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="catalog_product_save_after">
                                    <observer name="save_example_data" instance="VendorMyPackageObserverProductSaveAfter" />
                                    </event>
                                    </config>






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered yesterday









                                    Arshad SyedArshad Syed

                                    1




                                    1



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Magento Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f203904%2fmagento-2-how-to-get-current-product-name-in-an-observer%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Sum ergo cogito? 1 nng

                                        419 nièngy_Soadمي 19bal1.5o_g

                                        Queiggey Chernihivv 9NnOo i Zw X QqKk LpB