Magento – Magento2: Add new Field in Cart page and Save in order

magento2

I want to Add new Field "Remark" in Cart Items Page.
it is a purpose to "Remark" for product.
When i save cart(Update cart) it will be saved in Quote items table. also "Procced To checkout" It will be saved in order detials.
Also view in admin side

Best Answer

Magento provides additional attribute functionality to pass additional data. On cart page, create input field for remark then in custom module's events.xml, create an observer like below :

<?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="customremark" instance="Companyname\Modulename\Observer\customremark" />
    </event>

</config>

Then in observer, you can get this remark field from request

<?php

namespace Companyname\Modulename\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class SetAdditionalOptions implements ObserverInterface
{
    /**
     * @var RequestInterface
     */
    protected $_request;

    /**
     * @param RequestInterface $request
     */
    public function __construct(
        RequestInterface $request
    ) {
        $this->_request = $request;
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // Check and set information according to your need
        if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
            $product = $observer->getProduct();
            $additionalOptions = [];
            $additionalOptions[] = array(
                'label' => "Remark",
                'value' => "Your Information",
            );
            $observer->getProduct()->addCustomOption('additional_options', serialize($additionalOptions));
        }
    }
}

Hope this helps.

Related Topic