I am calling ajax request and performing add to cart functionality.

Here is my controller code,

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class UpgradeMember extends \Magento\Framework\App\Action\Action
{
    protected $formKey;   
    protected $cart;
    protected $product;
    protected $customerSession;
    private $productRepository;
    private $logger;
    public $_storeManager;
    protected $checkoutSession;
    protected $messageManager;
    protected $productFactory;

    public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Checkout\Model\Cart $cart,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Catalog\Model\Product $product,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Framework\Message\ManagerInterface $messageManager,
    \Magento\Catalog\Model\ProductFactory $productFactory
    ) {         
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->_storeManager = $storeManager;
        $this->product = $product;      
        $this->customerSession = $customerSession;
        $this->productRepository = $productRepository;
        $this->logger = $logger;
        $this->checkoutSession = $checkoutSession;
        $this->messageManager = $messageManager;
        $this->productFactory = $productFactory;
        parent::__construct($context);
    }

public function execute()
{
    $productData = $this->getRequest()->getPost('product_data');  //this is array of SKU  
    $productData = unserialize(base64_decode($productData));
    $customCoulmn = $this->getRequest()->getPost('custom_column');

    try{

        foreach ($productData as $productSku) : 
            $productId = $this->product->getIdBySku($productSku);
            $params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product_id' => $productId, //product Id
                    'qty'   => 1 //quantity of product                      
                    );

            $_product = $this->productFactory->create()->load($productId); 
            $item = $this->cart->getQuote()->getItemByProduct($_product);
            if($item){
                $quote = $this->cart->getQuote();                   
                $quote->updateItem($item->getId(), array( 'qty' => 1));
                $quote->setData('custom_column', $customData); // Fill your custom data
                $quote->save();
            }else{                  
                $this->cart->addProduct($_product, $params);
                $quote = $this->cart->getQuote();
                $quote->setData('custom_column', $customData); // Fill your custom data
                $quote->save();
            }

            //$this->cart->addProduct($_product, $params);
        endforeach;
            $this->cart->save();
            $status = 1;

        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addException($e,__('%1', $e->getMessage()));
            $status = 0;
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('error.'));  
            $status = 0;
    }
        $result = array();
        $result['status'] = $status;
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($result);
        return $resultJson;
}

}

Here I have created custom_column in quote_item table, so when this controller is hitting, I am adding the product to the cart, it is working fine, but I am not finding how can we update the value for my custom column,

Can anyone help me to achieve this please, Thanks for the help!!

有帮助吗?

解决方案

You can add the custom column data in your quote table by adding below code in your controller.

$quote->setData('custom_column', $customData); // Fill your custom data

EDIT:

Updated controller code

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class UpgradeMember extends \Magento\Framework\App\Action\Action
{
    protected $formKey;   
    protected $cart;
    protected $product;
    protected $customerSession;
    private $productRepository;
    private $logger;
    public $_storeManager;
    protected $checkoutSession;
    protected $messageManager;
    protected $productFactory;
    protected $quoteRepository;

    public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Checkout\Model\Cart $cart,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Catalog\Model\Product $product,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Framework\Message\ManagerInterface $messageManager,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Quote\Model\QuoteRepository $quoteRepository
    ) {         
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->_storeManager = $storeManager;
        $this->product = $product;      
        $this->customerSession = $customerSession;
        $this->productRepository = $productRepository;
        $this->logger = $logger;
        $this->checkoutSession = $checkoutSession;
        $this->messageManager = $messageManager;
        $this->productFactory = $productFactory;
        $this->quoteRepository = $quoteRepository;
        parent::__construct($context);
    }

    public function execute()
    {
        $productData = $this->getRequest()->getPost('product_data');  //this is array of SKU  
        $productData = unserialize(base64_decode($productData));
        $customCoulmn = $this->getRequest()->getPost('custom_column');

        try{

            foreach ($productData as $productSku) : 
                $productId = $this->product->getIdBySku($productSku);
                $params = array(
                        'form_key' => $this->formKey->getFormKey(),
                        'product_id' => $productId, //product Id
                        'qty'   => 1 //quantity of product                      
                        );

                $_product = $this->productFactory->create()->load($productId); 
                $item = $this->cart->getQuote()->getItemByProduct($_product);
                if($item){
                    $quote = $this->cart->getQuote();                   
                    $quote->updateItem($item->getId(), array( 'qty' => 1));
                    $quote->save();
                }else{                  
                    $this->cart->addProduct($_product, $params);
                }

                $this->updateQuoteData($this->cart->getQuote()->getId(), $societyName, $societyCode, $instituteName, $instituteCode);
                //$this->cart->addProduct($_product, $params);
            endforeach;

            $this->cart->save();
            $status = 1;

            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $this->messageManager->addException($e,__('%1', $e->getMessage()));
                $status = 0;
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('error.'));  
                $status = 0;
        }
            $result = array();
            $result['status'] = $status;
            $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultJson->setData($result);
            return $resultJson;
    }

    public function updateQuoteData($quoteId, $societyName, $societyCode, $instituteName, $instituteCode)
    {
        $quote = $this->quoteRepository->get($quoteId); // Get quote by id
        foreach($quote->getAllVisibleItems() as $item){
            $item->setData('local_society', $societyName);
            $item->setData('society_code', $societyCode);
            $item->setData('local_institute', $instituteName);
            $item->setData('institute_code', $instituteCode);
            $item->save();
        }
    }

}

Hope it helps!!!

其他提示

There is an event to save custom column value in quote table try below method

Vendor/Module/etc/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="checkout_cart_product_add_after">
        <observer name="add_custom_column_to_quote" instance="Vendor\Module\Observer\SaveToQuote" />
    </event>
</config>

Vendor\Module\Observer\SaveToQuote.php

<?php
namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class saveRentalToQuote implements ObserverInterface {

    /**
     * @param \Magento\Framework\Event\Observer $observer
     * saves rental fields to quote items
     */
    public function execute(\Magento\Framework\Event\Observer $observer) {
        $item = $observer->getEvent()->getData('quote_item');
        $item->setData('custom_column', 'value');            
    }
}
许可以下: CC-BY-SA归因
scroll top