Magento – Add to cart not working for configurable products on product listing page. Magento – 2

cartmagento2

The add to cart function is not working for configurable products on product listing page.

When selecting the configurable product options(color,size) of the product and then trying to add the product to the cart, the cart is not updating and instead I'm redirected to the product detail page.

The configurable products need to be added to the cart when on the product listing page rather than redirecting to the product detail page.

There are no errors in the console and the Network tab is also showing no errors.

After redirecting to product detail page a message appears on top that you need to select options for your item.I have already chosen the required options.
enter image description here

Thanks in advance.

Best Answer

You will need to create the form on listings page for add to cart.

<?php $postParams = $block->getAddToCartPostParams($_product); ?>
<form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
                                                    <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
                                                    <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
                                                    <?php echo $block->getBlockHtml('formkey')?>


                                                    <button type="submit"
                                                            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                                                            class="btn btn-primary action tocart">
                                                        <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                                    </button>
                                                </form>
Related Topic