Magento – Magento 2 – Prevent form submit on page reload when Product add from sample script to Magento Shopping Cart

cartevent-observermagento2module

Below sample PHP script will list simple/configurable product with add to cart button. When user clicks on submit button, it will redirect to Magento shopping cart page and selected product will be shown in cart with quantity.

<form id="addproduct" name="addproduct" method="post" action="http://localhost/magento-2/checkout/cart/">
    <table>
        <tr>
            <td>
                <input type="checkbox" name="prod_id[]" value="67" class="prod_chk" />Chaz Kangeroo Hoodie
            </td>
            <td>
                <input type="text" name="prod_qty[]" disabled="disabled" class="prod_txt" />
            </td>
            <td>
                Color:
                <select name="prod_color[]" disabled="disabled" class="prod_clr">
                    <option value="Black">Black</option>
                    <option value="Orange">Orange</option>
                    <option value="Gray">Gray</option>
                </select>
            </td>
            <td>
                Size:
                <select name="prod_size[]" disabled="disabled" class="prod_size">
                    <option value="S">S</option>
                    <option value="M">M</option>
                    <option value="L">L</option>
                    <option value="XL">XL</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="prod_id[]" value="1" class="prod_chk" />   Joust Duffle Bag
            </td>
            <td>
                <input type="text" name="prod_qty[]" disabled="disabled" class="prod_txt" />
            </td>
        </tr>
    </table>
        <input type="submit" value="Submit" name="submit" />
</form>

events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

    <event name="controller_action_predispatch_checkout_cart_index"> 
        <observer name="addproduct_display" instance="Vendor\Module\Observer\ThirdPartyAdd" />
    </event>
</config>

Observer.php

<?php

namespace Vendor\Module\Observer;

class ThirdPartyAdd implements \Magento\Framework\Event\ObserverInterface {

    public function __construct(
            \Magento\Store\Model\StoreManagerInterface $storeManager, 
            \Magento\Checkout\Model\Cart $cart, 
            \Magento\Catalog\Model\Product $product, 
            \Magento\Quote\Model\QuoteFactory $quote,
            \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->_storeManager = $storeManager;
        $this->_cart = $cart;
        $this->_product = $product;
        $this->quote = $quote;
        $this->_productFactory = $productFactory;
    }

    public function execute(\Magento\Framework\Event\Observer $observer) {

        if (isset($_POST['submit']) && $_POST['submit'] == 'Submit') {
            for ($i = 0; $i < sizeof($_POST['prod_id']); $i++) {

                $qty = $_POST['prod_qty'][$i];

                $productModel = $this->_productFactory->create();
                $product = $productModel->load($_POST['prod_id'][$i]);

                $product_type = $product->getTypeID();

                if ($product_type == 'simple') {
                    $params = array(
                        'qty' => $_POST['prod_qty'][$i],
                    );
                    $this->_cart->addProduct($product, $params);
                    $this->_cart->save();
                } if($product_type == 'configurable') {
                    $simple_products = $product->getTypeInstance()->getUsedProducts($product); 
                    $attributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);

                    foreach ($simple_products as $simple_product) {
                        $super_attributes = array();
                        foreach ($attributes as $attribute) {
                            foreach ($attribute['values'] as $value) {

                                if ($value['label'] == $_POST['prod_size'][$i]) {
                                    $super_attributes[$attribute['attribute_id']] = $value['value_index'];
                                }
                                if ($value['label'] == $_POST['prod_color'][$i]) {
                                    $super_attributes[$attribute['attribute_id']] = $value['value_index'];
                                }
                            }
                        }
                    }
                    $this->_cart->addProduct($product, array(
                        'qty' => $_POST['prod_qty'][$i],
                        'super_attribute' => $super_attributes
                    ));
                    $this->_cart->save();
                }
            }
        }
    }
}

Issue – After product is added to cart, when user reloads the page, it
again submit the form and runs the script to add product. How do I
prevent form submit when user reloads/refresh the cart page ?

Best Answer

You need to modify your observer code like this.

<?php

namespace Vendor\Module\Observer;

class ThirdPartyAdd implements \Magento\Framework\Event\ObserverInterface 
{
    protected $_request;

    public function __construct(\Magento\Framework\App\Request\Http $request) 
    {
       $this->_request = $request;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
      if ($this->_request->getFullActionName() != 'checkout_cart_index')   
      {
         // DO YOUR CODE HERE
      }
    } 
}
Related Topic