Question

I have a custom functionality for add to cart in product detail page.

Once button clicked, sending product id and adding product to the cart.

Used below code to implement it.

<input type="hidden" id="product-id" value="2" />
<button id="add-btn" >Add Item</button>
 <script>
  require(['jquery', 'jquery/ui'], function($) {
        $(document).ready(function($) {
         $('#add-btn').click(function(){
          var product_id = jQuery('#product-id').val();
            var additemUrl = "<?php echo $this->getUrl().'product/addproduct/additems' ?>";
                jQuery.ajax({
                     url: additemUrl,
                     type: "POST",
                     data : 'product_id='+product_id,
                     dataType: 'json',
                     showLoader: true,
                }).done(function(result) {                          
                        if(result.status == 'success'){
                        alert('success');
                        }else{
                            alert('error');
                        }                         

                }); 
        });
   });
  });
 </script>.

here is the code of my controller file.

Vendor\Product\Controller\AddProduct\AddItems.php

<?php

 namespace Vendor\Product\Controller\AddProduct;
 use Magento\Framework\Controller\ResultFactory;
 use Magento\Framework\App\Action\Action;
 use Magento\Framework\App\Action\Context;
 class AddItems extends \Magento\Framework\App\Action\Action
 {
  protected $formKey;   
  protected $cart;
  protected $product;
   public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Catalog\Model\ProductFactory $product,
     array $data = []
    ) {
     $this->formKey = $formKey;
     $this->cart = $cart;
     $this->product = $product; 
     }

  public function execute()
  {         
    $product_id = $this->getRequest()->getPost('product_id');
    $_product = $this->product->create()->load($product_id);
    $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product_id' => $product_id, //product Id
                'qty'   => 1 //quantity of product                
            );     
    if($_product){
      $this->cart->addProduct($_product, $params);   
     $status = 'success'; 
     }else{
        $status = 0;
    } 
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $resultJson->setData($result);
    return $resultJson;
    }
  }

The above code working fine and product added to the cart successfully.

I need to check some conditions once the button is clicked for some validations.

So i created afterAddtocart Plugin like below.

Module/etc/frontend/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> 
<type name="Magento\Checkout\Model\Cart">
    <plugin name="interceptAddingProductToCart" 
    type="Vendor\Module\Plugin\Cart" sortOrder="10" disabled="false" />
</type>

then Module/Plugin/Cart.php

namespace Vendor\Module\Plugin;
class Cart
{
protected $request;
/**
 * Plugin constructor.
 *
 * @param \Magento\Checkout\Model\Session $checkoutSession
 */
public function __construct(
    \Magento\Framework\App\Request\Http $request 
) {
     $this->request = $request;   
}
 public function afterAddProduct($subject,$result)  
 {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $objectManager->get('Psr\Log\LoggerInterface')->info('test');        
    // I am looking for code how to get the clicked product id here
    return $this->rulehelper->getAgeRestriction();
  }
 }

Once the button clicked now the plugin file is loading, but i need to get the product info in this plugin file.

Can anyone look into this and help me how to get the product data in the Plugin file.

Thanks

Was it helpful?

Solution

You are able to access the arguments passed to the original method as below:

 public function afterAddProduct($subject,$result, $product, $params)  
 {

 }
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top