Question

In Magento 2.4.2 "Add to Cart" button is disabled in template and is being enabled using js post initialization

vendor/magento/module-catalog/view/frontend/templates/product/list.phtml

<button type="submit" 
    title="<?= $escaper->escapeHtmlAttr(__('Add to Cart')) ?>" 
    class="action tocart primary" 
    disabled>
    <span><?= $escaper->escapeHtml(__('Add to Cart')) ?></span>
</button>

vendor/magento/module-catalog/view/frontend/web/js/catalog-add-to-cart.js

_create: function () {
    if (this.options.bindSubmit) {
        this._bindSubmit();
    }
    $(this.options.addToCartButtonSelector).attr('disabled', false);
}

Can anyone help me with reason behind this approach? It wasn't there in Magento 2.4.1. Thanks in advance.

Was it helpful?

Solution

It appears there was an issue with invalid form key errors when add to cart was clicked before the page was fully loaded.

The change ensures that the add to cart button is enabled only when the page is fully loaded and catalog-add-to-cart.js has been processed.

The commit from August 2020 can be seen here https://github.com/magento/magento2/commit/95859dc036a6076423f30409f224a6b5d6f5ac84

This change will cause problems if you are extending catalog-add-to-cart.js in your custom theme or modules. You should update your custom/extended js to activate the add to cart button.

$(this.options.addToCartButtonSelector).attr('disabled', false);

OTHER TIPS

Go to this file path

vendor/magento/module-catalog/view/frontend/templates/product/list.phtml

Click ctrl+F and search for action tocart primary

<button type="submit" title="<?= $escaper->escapeHtmlAttr(__('Add to Cart')) ?>"class="action tocart primary">
<span><?= $escaper->escapeHtml(__('Add to Cart')) ?>
</span></button>

Just replace button tag with this code and run (As you mentioned in comments disabled is there just remove or replace the button tag with above code)

For ubuntu

sudo rm -rf generated/* var/* && sudo bin/magento cache:flush

For windows

rm -rf generated/* var/* && php bin/magento cache:flush
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top