Magento 2: Save value to a custom field in the order

Magento 2 Save value to a custom field in the order

We have created a custom field in the quote table and saved the value. This post will create a field in the sales_order table to save a custom.

We are often required to save additional data into the sales_order table to display on the front or back end. Also, we must share this data with a third-party ERP system using an API. Adobe Commerce, or Magento 2, is mighty easy to customize. It is easy to add or customize the feature in Magento 2.

E-commerce recommends data collection from the customer to provide excellent customer service. Although Adobe Commerce or Magento 2 captures almost all possible data when placing an order, we often need additional data from the customer. Like an extra comment for the shipping, a further requirement for the product, etc.

We can achieve such requirements quickly. We need to create a field inside the sales_order table, and we can save the value into it by using a plugin or event observer. The data source can be a quote, custom table, checkout session, extension attributes, or system configuration (Checkout Configuration).

As we have already created a field in the quote table and saved data, we will use quote as a data source in this post.

We will create a field named sbdevblog_comment and save a demo comment.

Magento 2: Save value to a custom field in the order

So, let’s create a custom field inside the sales_order table using declarative schema.

<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="sales_order" resource="default" engine="innodb">
        <column name="sbdevblog_comment" nullable="true" xsi:type="varchar" length="50" comment="SbDevBlog Comment"/>
    </table>
</schema>

The above code will create a field inside the sales_order table. Let’s save the value using an event observer. The event named sales_model_service_quote_submit_before is used to save values into the sales_order table.

<?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="sales_model_service_quote_submit_before">
        <observer name="saving_sb_dev_blog_comment_to_order" instance="SbDevBlog\Checkout\Observer\SaveSbDevBlogComment"/>
    </event>
</config>

It’s time to create an observer class that saves the comment into the created field.

<?php

namespace SbDevBlog\Checkout\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Api\CartRepositoryInterface;
use Psr\Log\LoggerInterface;

class SaveSbDevBlogComment implements ObserverInterface
{
    /**
     * @var CartRepositoryInterface
     */
    private CartRepositoryInterface $cartRepository;

    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * @param CartRepositoryInterface $cartRepository
     * @param LoggerInterface $logger
     */
    public function __construct(
        CartRepositoryInterface $cartRepository,
        LoggerInterface $logger
    ) {
        $this->cartRepository = $cartRepository;
        $this->logger = $logger;
    }

    /**
     * Saving Sb Dev Blog Order Comment
     *
     * @param EventObserver $observer
     * @return void
     */
    public function execute(EventObserver $observer)
    {
        try {
            $order = $observer->getOrder();
            $quote = $this->cartRepository->get($order->getQuoteId());
            $order->setData("sbdevblog_comment", $quote->getData("sbdevblog_comment"));
        } catch (NoSuchEntityException $e) {
            $this->logger->error($e->getMessage());
        }
    }
}

That’s it. Thank you for reading the post – Magento 2: Save value to a custom field in the order. Please subscribe and share with your connections. Also, please feel free to use the comment section for your feedback.

Download Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *