0

I am creating a custom form essentially from scratch. The form will be an alternative UI for a product page, which when submitted, does the same thing as the normal add to cart.

I'd like to borrow from the checkout/cart/add controller without copying or rewriting the code, but before I submit I need to run own custom function (to create a file).

Is there any way I can achieve this? Eg, is there an event for an Observer I can use or is it possible to have two Controllers execute one after the other?

1 Answer 1

0

The answer was pretty obvious, not sure why I didn't think of this originally. Simply extend the controller and return parent::execute().

namespace Vendor\Module\Controller\Custom;

use Magento\Checkout\Controller\Cart\Add as AddToCart;

class Add extends AddToCart {

    public function execute()
    {

        $this->dothing();

        return parent::execute();

    }
    public function dothing()
    {
        // custom code
    }
}

As a bonus I also learned recently that the Action class has predispatch and post dispatch events that can be hooked into with an Observer, allowing you to run code before or after a controller has fired.

//from Magento\Framework\App\Action\Action
$this->_eventManager->dispatch('controller_action_predispatch', 
$eventParameters);
    $this->_eventManager->dispatch('controller_action_predispatch_' . 
$request->getRouteName(), $eventParameters);
    $this->_eventManager->dispatch(
        'controller_action_predispatch_' . $request->getFullActionName(),
        $eventParameters
    );

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.