0

What I am trying to achieve is when a product is added to the cart, the customer will have the option to add a special gift box. As every product has a different gift box and price so to do this what I did is added product id of gift box into input type hidden fields on product view page and when user is clicking on add to cart, I can have the gift box id in additional option in params of the cart. and by using that gift box id, I can add the giftbox product to cart as well.

I tried using the plugin, but it is not working. can anyone help me to see what is wrong?

Here is my di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">    
    <type name="Magento\Checkout\Controller\Cart\Add">
        <plugin name="SamaaAdditionCart" type="Samaa\AdditionalCart\Plugin\AddPlugin" sortOrder="10"/>
    </type>
</config>

AND here is my AddPlugin.php

namespace Samaa\AdditionalCart\Plugin;

class AddPlugin
{        
    public function aroundExecute(\Magento\Checkout\Controller\Cart\Add $subject, \Closure $proceed)
    {

        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            $this->messageManager->addErrorMessage(
                __('Your session has expired')
            );
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }

        $params = $this->getRequest()->getParams();




        try {
            if (isset($params['qty'])) {
                $filter = new \Zend_Filter_LocalizedToNormalized(
                    ['locale' => $this->_objectManager->get(
                        \Magento\Framework\Locale\ResolverInterface::class
                    )->getLocale()]
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            $product = $this->_initProduct();
            $related = $this->getRequest()->getParam('related_product');

            if (!$product) {
                return $this->goBack();
            }

            if(isset($params['options']))
            {
                if(isset($params['options']['additional_product_option']));
                {
                    $addition_product_id = $params['options']['additional_product_option'];
                    if(is_numeric($addition_product_id) && $addition_product_id!="")
                    {

                            $storeId = $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class)->getStore()->getId();  
                            $giftBoxproduct = $this->productRepository->getById($addition_product_id, false, $storeId);
                            $giftBoxProductParameters = array('product' => $addition_product_id,
                                'qty' => $params['qty'],
                                 'form_key' => $params['form_key']
                            );  
                            $this->cart->addProduct($giftBoxproduct, $giftBoxProductParameters);
                            unset($params['options']['additional_product_option']);
                    }

                }
            } 


            $this->cart->addProduct($product, $params);
            if (!empty($related)) {
                $this->cart->addProductsByIds(explode(',', $related));
            }

            $this->cart->save();

            /**
             * @todo remove wishlist observer \Magento\Wishlist\Observer\AddToCart
             */
            $this->_eventManager->dispatch(
                'checkout_cart_add_product_complete',
                ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
            );

            if (!$this->_checkoutSession->getNoCartRedirect(true)) {
                if (!$this->cart->getQuote()->getHasError()) {
                    if ($this->shouldRedirectToCart()) {
                        $message = __(
                            'You added %1 to your shopping cart.',
                            $product->getName()
                        );
                        $this->messageManager->addSuccessMessage($message);
                    } else {
                        $this->messageManager->addComplexSuccessMessage(
                            'addCartSuccessMessage',
                            [
                                'product_name' => $product->getName(),
                                'cart_url' => $this->getCartUrl(),
                            ]
                        );
                    }
                }
                return $this->goBack(null, $product);
            }
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            if ($this->_checkoutSession->getUseNotice(true)) {
                $this->messageManager->addNoticeMessage(
                    $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($e->getMessage())
                );
            } else {
                $messages = array_unique(explode("\n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->messageManager->addErrorMessage(
                        $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($message)
                    );
                }
            }

            $url = $this->_checkoutSession->getRedirectUrl(true);

            if (!$url) {
                $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
            }

            return $this->goBack($url);
        } catch (\Exception $e) {
            $this->messageManager->addExceptionMessage(
                $e,
                __('We can\'t add this item to your shopping cart right now.')
            );
            $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
            return $this->goBack();
        }

    }
}

  • showing any error ??? – Mohit Patel Apr 24 '20 at 21:30
  • i think use this line --- <plugin name="Samaa_AdditionalCart_addPlugin" type="Samaa\AdditionalCart\Plugin\AddPlugin" sortOrder="1" /> – Mohit Patel Apr 24 '20 at 21:41
  • Hi @MohitPatel No error no logs – Rahul Thakral Apr 25 '20 at 6:55
  • I have above add new line try... – Mohit Patel Apr 25 '20 at 7:28
  • @MohitPatel Tried the same but not working – Rahul Thakral Apr 25 '20 at 7:52
0

You have to tried with Over ride controller for such functionality rather then create Plugin on that. use preference of that controller and do your custom code with each Product add to cart that easily you can manager and also handle it.

Let me know if you have still query.

Thanks

  • As I know, Add.php in the cart controller is an abstract controller, which means override won't work.@Nirav Gohel – Rahul Thakral May 7 '20 at 19:31

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.