Skip to content

Knowing which button was clicked on the product page in an observer?

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!