0

I'm using this plugin in order to prevent a product be added more than one time and it works perfectly but I'd like to add a feature: instead to stay on the product page once the product is added more than one time, I'd like to check if the backend option Stores->Configuration->Sales->Checkout->Shopping Cart->After Adding a Product Redirect to Shopping Cart is enabled and redirect if it is.

di.xml

<type name="Magento\Checkout\Model\Cart">
    <plugin disabled="false" name="Vendor_Module_Plugin_Magento_Checkout_Cart_BeforeAddToCart" type="Vendor\Module\Plugin\Magento\Checkout\Cart\BeforeAddToCart"/>
</type>

vendor/module/Plugin/Magento/Checkout/Cart/BeforeAddToCart.php

<?php
declare(strict_types=1);

namespace Vendor\Module\Plugin\Magento\Checkout\Cart;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
use Magento\Checkout\Model\Session\Proxy as SessionProxy;
use Magento\Framework\Message\ManagerInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;

class BeforeAddToCart {

    protected $messageManager;
    protected $cartSession;
    protected $configurableProduct;

    public function __construct(
        Configurable $configurableProduct,
        ManagerInterface $messageManager,
        SessionProxy $cartSession
    ) {
        $this->messageManager = $messageManager;
        $this->cartSession = $cartSession;
        $this->configurableProduct = $configurableProduct;
    }

    public function beforeAddProduct(Cart $subject, $productInfo, $requestInfo=null)
    {
        $enableProductCartControl=true;

        $product = null;
        $parentProduct=null;

        if ($productInfo instanceof Product) {

            $product = $productInfo;
            if (!$product->getId()) {
                throw new \Magento\Framework\Exception\LocalizedException(
                    __("The product wasn't found. Verify the product and try again.")
                );
            }

        }

        if ($product)
        {
            if ($product->getTypeId()==='configurable')
            {
                if (isset($requestInfo['super_attribute']))
                {
                    $parentProduct=$product;
                    $childProduct = $this->configurableProduct->getProductByAttributes($requestInfo['super_attribute'] ,$product);
                    // change $product to child
                    $product=$childProduct;
                }
            }

            if ($product->getTypeId()==='grouped')
            {
                if (isset($requestInfo['super_group']))
                {
                    $parentProduct=$product;
                    //$childProduct = // get child from grouped...
                    // change $product to child
                    //$product=$childProduct;
                }
            }
                if ($product && $enableProductCartControl)
                {
                    // check for existence of product in cart...
                    //
                    if($this->cartSession->getQuote()->hasProductId($product->getId())){
                        
                        throw new \Magento\Framework\Exception\LocalizedException(
                            __("This product is already in the cart. Testing, testing : ". $product->getSku())
                        );
                    }

                }


        }

        return [$productInfo, $requestInfo];

    }

    /**
     * Get request for product add to cart procedure
     *
     * @param \Magento\Framework\DataObject|int|array $requestInfo
     * @return \Magento\Framework\DataObject
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    private function _getProductRequest($requestInfo)
    {
        if ($requestInfo instanceof \Magento\Framework\DataObject) {
            $request = $requestInfo;
        } elseif (is_numeric($requestInfo)) {
            $request = new \Magento\Framework\DataObject(['qty' => $requestInfo]);
        } elseif (is_array($requestInfo)) {
            $request = new \Magento\Framework\DataObject($requestInfo);
        } else {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('We found an invalid request for adding product to quote.')
            );
        }
        return $request;
    }
}
1
  • I updated the answer to your original question with the cart redirect.
    – paj
    Feb 24, 2021 at 9:53

2 Answers 2

1

In this case the plugin is working with Magento\Checkout\Model\Cart you can simply set a redirect url in the session

$this->session->setRedirectUrl($this->url->getUrl('checkout/cart/index'));

Inject the following classes

 Magento\Checkout\Model\Session $session 
 Magento\Framework\UrlInterface $url
2
  • Thanks @paj. It partially works. I mean, it redirect to the cart page even if the product is already present but it doesn't check the backend option Stores->Configuration->Sales->Checkout->Shopping Cart->After Adding a Product Redirect to Shopping Cart. Furthermore, once redirected it shows this message We can't add this item to your shopping cart right now..
    – KaMZaTa
    Feb 25, 2021 at 0:01
  • pastebin.com/ns3vSdFr
    – KaMZaTa
    Feb 25, 2021 at 2:09
0
  1. You can use the vendor/magento/module-checkout/Helper/Cart.php helper's method getShouldRedirectToCart() to check if your configuration is enabled.
  2. You can use the same helper's getCartUrl() method to retrieve the URL of the cart page.
  3. Inject in your plugin constructor the \Magento\Framework\Controller\Result\RedirectFactory class and store it in a private property called $resultFactory, then use it like this to redirect to cart the desirec URL (just store the cart url in the $redirectUrl variable):
 /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl($redirectUrl);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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