0

Magento 2.4.6

I added a button to my addtocart.phtml. Below the button I added a hidden field, like this:

<button type="submit" 
        title="<?= $buttonSampleTitle ?>" 
        class="action primary sample tocart"
        id="product-sample-button">
    <span>
        <?= $buttonSampleTitle ?>
    </span>
</button>
<input type="hidden" id="is-sample" name="is-sample" value="0" />

Now I created an observer listening to the controller_action_predispatch_checkout_cart_add event. Doing so, I can read out the is-sample value in the observer like this:

$isSample = $observer->getRequest()->getParam('is-sample');

The problem is, I need to modify (change name and price) the quote item in the same observer, which doesnt work. It only works when I use the checkout_cart_product_add_after event. With that event on the other hand, I can not read the is-sample parameter in the observer.

Is there a way to make it work together? Or maybe there is another way of adding a button to my template and knowing it was clicked in the checkout_cart_product_add_after event?

Thanks for helping!

1 Answer 1

0

You can still get the request when using checkout_cart_product_add_after, it's just not included in the observer params, so you need to include it in your class manually:

<?php
namespace Namespace\Module\Observer;

class Observer implements \Magento\Framework\Event\ObserverInterface {
    private \Magento\Framework\App\RequestInterface $request;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request
    ) {
        $this->request = $request;
    }
    
    public function execute(\Magento\Framework\Event\Observer $observer): void {
        $isSample = $this->request->getParam('is-sample');
        
        // Rest of code
    }
}
1
  • Awesome, works like a charm! Thanks! May 31, 2023 at 6:27

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.