Showing results for 
Search instead for 
Did you mean: 

How to listen events?

How to listen events?

Hey everyone,


I am pretty new in Magento 2. I didn't figure out how to listen action events. For example, I try to add a product to card(btw using default add button), but it does not add to card. Here is the default add button in grid.phtml :



 $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
 $postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()]);?>
  <button class="action tocart primary" data-post='<?php /* @escapeNotVerified */ echo  $postData ?>'
  type="button" title="<?php /* @escapeNotVerified */ echo __('Add to Cart') ?>">
  <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>

When I click the button, It redirect me to checkout/card page, but there is no items in there. So, I tried to add manually and I implemented new function to button instead of default functions:

 <button data-post='<?php echo $this->addProductToCartManually($_item->getEntityId()); ?>'><img src="/magento/pizza/images/home2/menuBtn.png" type="button"></button>

And my function: 

    public function addProductToCartManually($product) { 
        $om = \Magento\Framework\App\ObjectManager::getInstance();
        $cart = $om->get('Magento\Checkout\Model\Cart'); 
        $request = $om->get('Magento\Framework\App\Action\Context')->getRequest();
        $frontcontroller = $om->get('Magento\Framework\App\FrontControllerInterface');
        $productObj = $request;
        $productObj = (string)$productObj;
        $pos = strpos($productObj, "POST"); //return true if exits
        $pos = (int)$pos;
        $pos = + 1;
        if ($pos) {

	        $cart->addProduct($product, 1);
        //$contextModel = $om->get('Magento\Framework\App\Helper\Context');

        return $pos;

But it adds all products instead of product, which I added as clicking button. So, can someone help me how to listen action events. Thank you!




Re: How to listen events?

Use debugger's breakpoints.
You can do it for both the JavaScript and PHP.