cancel
Showing results for 
Search instead for 
Did you mean: 

Hey everyone, help me !!!!!!!!

Hey everyone, help me !!!!!!!!

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 :

 

 <?php

 $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>
 </button>

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);	        $cart->save(); 
        }
        //$contextModel = $om->get('Magento\Framework\App\Helper\Context');

        //$cart->truncate();
        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!

 

1 REPLY 1

Re: Hey everyone, help me !!!!!!!!

@jupite_rsea Hey, Could you please share what is the exact functionality do you need. So, I will do some code changes which you have shared in the post.