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="Vendor\Module\Observer\CheckoutCartSaveAfterObserver" />
   </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?

2

1.oneway:

public function execute(\Magento\Framework\Event\Observer $observer)
            {
               //Product get product name
               $observer->getProduct()->getName();
            }

2.Registry:

$this->product = $this->registry->registry('product');
$this->product->getName();
| 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;
    }
| 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 Magento\Checkout\Model\Cart 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(); 
        }

    }
| 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

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 \Magento\Checkout\Model\Cart $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 \Magento\Catalog\Api\ProductRepositoryInterface
 */
protected $productRepository;

/**
 * CheckoutCartSaveAfter constructor.
 *
 * @param \Magento\Catalog\Api\ProductRepositoryInterface $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 \Magento\Catalog\Model\Product[] $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 Vendor\Module\Observer;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class CheckoutCartSaveAfter implements ObserverInterface
{
/**
 * @var \Magento\Catalog\Api\ProductRepositoryInterface
 */
protected $productRepository;

/**
 * CheckoutCartSaveAfter constructor.
 *
 * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
 */
public function __construct(ProductRepositoryInterface $productRepository)
{
    $this->productRepository = $productRepository;
}

/**
 * {@inheritdoc}
 */
public function execute(Observer $observer)
{
    /** @var \Magento\Checkout\Model\Cart $cart */
    $cart = $observer->getData('cart');

    $productIds = $cart->getQuoteProductIds();

    /** @var \Magento\Catalog\Model\Product[] $products */
    $products = [];
    foreach ($productIds as $productId) {
        $products[$productId] = $this->productRepository->getById($productId);
    }

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

}
| improve this answer | |
0

You need create file inside app\code\Vendor\MyPackage\Observer\ProductSaveafter.php

<?php
namespace Vendo\MyPackage\Observer;
    use \Magento\Framework\Event\ObserverInterface;
    use \Magento\Framework\Event\Observer as EventObserver;

    class ProductSaveAfter implements ObserverInterface
    {

    public function execute(\Magento\Framework\Event\Observer $observer)
        {
            /** @var \Magento\Catalog\Model\Product $product */
            $product = $observer->getEvent()->getProduct();
            $productID=$product->getId();            
                var_dump($productID);
                die();
        }

Next another file app\code\Vendor\MyPackage\etc\adminhtml\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="catalog_product_save_after">
        <observer name="save_example_data" instance="Vendor\MyPackage\Observer\ProductSaveAfter" />
    </event>
</config>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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