2

i have added new column in 'quote_item' table. i want to add the data to custom column when user add any product to cart.

0

You can use event/observer to achieve this.

Use following codes in your module.

etc/frontend/events.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_add_product_complete">
        <observer name="bialcheckout_product_add_to_cart" instance="Vendor\Module\Observer\ProductAddToCart" />
    </event>
</config>

Observer/ProductAddToCart.php

<?php
namespace Vendor\Module\Observer;

use Magento\Checkout\Model\Session;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Quote\Model\QuoteRepository;

class ProductAddToCart implements ObserverInterface
{
    public function __construct(
        Session $session,
        QuoteRepository $quoteRepository
    )
    {
        $this->session = $session;
        $this->quoteRepository = $quoteRepository;
    }

    public function execute(Observer $observer)
    {
        $quoteId = $this->session->getQuote()->getId();
        if ($quoteId) {
            $quote = $this->quoteRepository->get($quoteId);
            if (!$quote->getIsActive()) {
                return;
            }

        $product = $observer->getEvent()->getDataByKey('product');
        /** @var \Magento\Quote\Model\Quote\Item $item */
        $item = $this->session->getQuote()->getItemByProduct($product);
        $itemId = $item->getId();
        $quoteItem = $quote->getItemById($itemId);
        $customValue = 10;  // Prepare your custom field value here
        $quoteItem->setCustomField($customValue); // Set custom field value
        $quoteItem->save();
        }
        return $this;
    }
}
| improve this answer | |

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.