0

I added some custom field(receipent_email) in quote_item table.

When user adding item in cart, I m sending custom data to cart item.

Data is saving in quote_item table perfectly.

Also i split item in cart by (recipient_email) id. If a same simple product have two different recipient_email,its splitting in cart, Not merging like quantity increase.

But Suppose i have a product by product id 121.

I m adding that product in cart with custom data(recipient_email). If i added data in cart first time with email(abc@gmail.com),then its splitting as per code.

But if user adding same recipient_email with same product, then it should increase quantity of product in quote_item,which row have recipient_email.

I tried for split(working fine)

Magento\Quote\Model\Quote\Item::representProduct()

Implementation

public function representProduct($product) {   //echo print_r(get_class_methods($this));exit;
        $itemProduct = $this->getProduct();
        if (!$product || $itemProduct->getId() != $product->getId()) {
            return false;
        }

        /**
         * Check maybe product is planned to be a child of some quote item - in this case we limit search
         * only within same parent item
         */
        $stickWithinParent = $product->getStickWithinParent();
        if ($stickWithinParent) {
            if ($this->getParentItem() !== $stickWithinParent) {
                return false;
            }
        }

        // Check options
        $itemOptions = $this->getOptionsByCode();
        $productOptions = $product->getCustomOptions();

        if (!$this->compareOptions($itemOptions, $productOptions)) {
            return false;
        }
        if (!$this->compareOptions($productOptions, $itemOptions)) {
            return false;
        }

        // For Product gift
        $items = $this->getQuote()->getAllVisibleItems();
        $recipientEmail = $this->_request->getPost('gift-recipient-email');
        if (!empty($recipientEmail)) {
            if (count($items) > 0) {
                foreach ($items as $item) { 
                    if($item->getData('gift_recipient_email') == $recipientEmail){
                        return true;
                    }
                }
            } 
            return false;
        }

        return true;
    } 

If user adding same product,with same email,it should increase quantity in quote_item which row have gift_recipient_email = request('email'), But its not working...

Code for email validation

Magento\Checkout\Controller\Cart\Add::execute();

public function execute() {
        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }

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


        if (array_key_exists('message-type', $params)) {
            $messageType = $params['message-type'];
            unset($params['message-type']);
        }


            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');

                /**
                 * Check product availability
                 */
                if (!$product) {
                    return $this->goBack();
                }
                // Validation of receipent email
                --------------------------------Start---------------------------------------
                if ($params['gift-recipient-email']) {
                    $quote = $this->cart->getQuote()->getAllVisibleItems();
                    $quoteId = $this->cart->getQuote()->getId();
                    foreach ($quote as $item) {

                        if ($item->getGiftRecipientEmail() == $params['gift-recipient-email']) { 
                            $this->cart->getQuote()->updateItem($item->getItemId(),$params);
                        }
                    }

                }else{

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

                $this->cart->save();
               ----------------------------------------End-------------------------------------------------

                /**
                 * @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->addNotice(
                            $this->_objectManager->get(\Magento\Framework\Escaper::class)->escapeHtml($e->getMessage())
                    );
                } else {
                    $messages = array_unique(explode("\n", $e->getMessage()));

                    foreach ($messages as $message) {

                        $this->messageManager->addError(
                                $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->addException($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();
            }
        }
  • why are you not working with buyRequests? – Philipp Sander Jan 21 at 11:55
  • @PhilippSander But request have produt id and some data...but i need item id by email id. – Deepak Rai Jan 21 at 11:57

Your Answer

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

Browse other questions tagged or ask your own question.