5

I have create event controller_action_predispatch_checkout_cart_add as given below:

Vendor/Module/etc/frontend/events.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_checkout_cart_add">
        <observer name="bialcheckout_before_product_add_to_cart" instance="Vendor\Module\Observer\ProductBeforeAddToCart" />
    </event>
</config>

Vendor/Module/Observer/ProductBeforeAddToCart.php

<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class ProductBeforeAddToCart implements ObserverInterface {
 public function __construct(
// dependencies
){
....
}
public function execute(Observer $observer)
{ 
    $productId = $observer->getRequest()->getParam('product');
    $superAttributes = $observer->getRequest()->getParam('super_attribute');
    // Rest of the code
}
}

Above code works fine if I add product from product details page. Now in one of my custom module, I am adding product to cart programatically. After product is added to cart programatically, above method is not executed automatically. From my custom module I want to call my code written in the above observer with product data. How I can do that?

I mean, How to trigger a observer programatically with it's required data from a custom controller file ?

2 Answers 2

5

You can try to add this below code in your controller :

/**
 * Core event manager proxy
 *
 * @var \Magento\Framework\Event\ManagerInterface
 */
protected $_eventManager;

public function __construct(
    .....
    \Magento\Framework\Event\ManagerInterface $eventManager,
    .....
) {
    .....
    $this->_eventManager = $eventManager;
    .....
}

public function execute()
{
    //your code
    //you can pass param value and set condition here as per your requirement. 
    $this->_eventManager->dispatch(
                'controller_action_predispatch_checkout_cart_add',
                ['category' => $category, 'request' => $this->getRequest()]
            );
}
1

In addition to what Rohan as shared, You can prepare your parameters as given below:

<?php
namespace Vendor\Module\Controller\Index;
class AddToCart extends \Magento\Framework\App\Action\Action {
   public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute,
    \Magento\Framework\Event\ManagerInterface $eventManager,
    \Magento\Framework\App\RequestInterface $request,
     \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
)
{
    parent::__construct($context);
    $this->_cart = $cart;
    $this->productRepository = $productRepository;
    $this->eavAttribute = $eavAttribute;
    $this->eventManager = $eventManager;
    $this->jsonFactory = $jsonFactory;
    $this->request = $request;
}

    public function execute() {

        $sizeAttributeId = $this->eavAttribute->getIdByCode('catalog_product', 'size');
        $colorAttributeId = $this->eavAttribute->getIdByCode('catalog_product', 'color');
        $parentProductId = $this->getRequest()->getParam('parentId');
        $colorOptionId = $this->getRequest()->getParam('colorOptionId');
        $sizeOptionId = $this->getRequest()->getParam('sizeOptionId');
        $qty = $this->getRequest()->getParam('qty');

        $result = $this->jsonFactory->create();

        $options = array(
                        $colorAttributeId => $colorOptionId,
                        $sizeAttributeId => $sizeOptionId
                    );

        $params = array(
            'product' => $parentProductId,
            'super_attribute' => $options,
            'qty' => $qty
        );

        $this->request->setPostValue('product', $parentProductId); // prepare your parameters
        $this->request->setPostValue('super_attribute', $options);
        $this->request->setPostValue('qty', $qty);

        $product = $this->productRepository->getById($parentProductId);
        $this->_cart->addProduct($product,$params);
        $this->eventManager->dispatch(
        'controller_action_predispatch_checkout_cart_add',
                ['product' => $product, 'request' => $this->request]
                );
        $this->_cart->save();
        return $result->setData(['status' => 200]);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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