1

In magento 2, by default, if I try to add configurable products to cart when not selecting any swatch values, I will be redirect to product page.

enter image description here

How can I prevent this and display a message like in product detail page instead of redirecting? enter image description here

1

To achieve an output similer to product detail page in product list page,

So copy list.phtml file from vendor/magento/module-catalog/view/frontend/templates/product/list.phtml into your theme if not exist

so the new path will be something similer to app/design/frontend/[NAMESPACE]/[THEME]/Magento_Catalog/templates/product/list.phtml

then in list.phtml file find below code and replace

<?php if (!$block->isRedirectToCartEnabled()) : ?>
    <script type="text/x-magento-init">
    {
        "[data-role=tocart-form], .form.map.checkout": {
            "catalogAddToCart": {
                "product_sku": "<?= /* @NoEscape */ $_product->getSku() ?>"
            }
        }
    }
    </script>
<?php endif; ?>

with

<?php if (!$block->isRedirectToCartEnabled()) : ?>   
    <script type="text/x-magento-init">
    {
        "[data-role=tocart-form], .form.map.checkout": {
            "Magento_Catalog/js/validate-product": {}
        }
    }
    </script>
<?php endif; ?>

After replacing code, flush the cache (php bin/magento cache:flush) and see the store front, will get expected output.

logic will work like product detail page more reference find code in vendor/magento/module-catalog/view/frontend/templates/product/view/addtocart.phtml

Sample output for all the scenarioes with Magento LUMA product list page :

sample output

Note : CSS work need. hope that can be done easily.

7
  • Thank you! I did it! – Hieu Duong Aug 6 '19 at 3:46
  • @HieuDuong, you'r welcome, thanks for accepting answer, if you like my answer please do up vote also. :) – Kanhaiya lal Aug 6 '19 at 8:17
  • I did up vote but the number will not increase due to my reputaion. – Hieu Duong Aug 6 '19 at 8:50
  • @HieuDuong no issue :) – Kanhaiya lal Aug 7 '19 at 8:00
  • 1
    @SagarParikhSGR Yes, this is possible but JS code change required, can be make all validation message to popup message for globally or page specific via JS override or via JS Mixin. – Kanhaiya lal Dec 17 '19 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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