Magento 2 How To Use Quote Submit Event as sales_model_service_quote_submit_before

When you want to save data to the sales_order table from the quote table OR before place an order you want to save data to the sales_order table, you can achieve this with the event observer approach.

You can save custom field value to the sales_order table before the order placed. The provided event will be useful to copy quote table data to the sales_order table.

Event Name: sales_model_service_quote_submit_before

The event will be useful for adding extra custom_fee to the order total and saves the custom_fee value to the sales_order table once the order is placed successfully.

You have to create an entry for the custom_fee in the quote and sales_order total.

Define Events in the events.xml file:

<?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="sales_model_service_quote_submit_before">
        <observer name="save_custom_fee" instance="Magemeta\CustomFee\Observer\AddCustomFee" />
    </event>
</config>

Now Create an Observer file to Handle Logic once trigger an action for the event,

<?php declare(strict_types=1);
/**
 * Save Custom Fee in sales_order before place an order.
 */
 
namespace Magemeta\CustomFee\Observer;
 
use Exception;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
 
class AddCustomFee implements ObserverInterface
{
    /**
     * @param Observer $observer
     * @return $this;
     * @throws Exception
     */
    public function execute(Observer $observer)
    {
        $event = $observer->getEvent();
        // Get Order Object
        /* @var $order \Magento\Sales\Model\Order */
        $order = $event->getOrder();
        // Get Quote Object
        /** @var $quote \Magento\Quote\Model\Quote $quote */
        $quote = $event->getQuote();
 
        if ($quote->getCustomFee()) {
            $order->setCustomFee($quote->getCustomFee());
        }
        return $this;
    }
}

Before placing an order, we are checking for the Quote Object using $quote and checking like the custom fee is set or not in the quote table.

If the custom fee is available in the quote table, we can get it using $quote->getCustomFee() and set it to the $order object.

Given code snippet automatically saves custom fee value to the custom_fee column in the order table.

We can use this event whenever you need to save data to the sales_order table from the quote table or you can use this event as per your need of customization.

Leave a Reply