I have followed the below steps to create an order in magento 2. But i want to set my preference date when creating it.

How to create order programmatically in Magento 2?


I think you can observe the event sales_model_service_quote_submit_before and set the created_at field in there.
This event is dispatched before the order is persisted in the db and you get as parameter the order object.
But this event gets dispatched for every order. So you have to mark your "manual" orders somehow.

So in the script that creates the quote you can do something like this before $order = $this->quoteManagement->submit($quote);:

$quote->setData('is_manual_order', true); 

and your event observer can look like this:

namespace Vendor\Module\Observer;

class QuoteSubmitBefore implements \Magento\Framework\Event\ObserverInterface
    public function execute(\Magento\Framework\Event\Observer $observer)
        $quote = $observer->getQuote();
        $order = $observer->getOrder();
        if ($quote && $order && $quote->getData('is_manual_order')) {
            $order->setCreatedAt(your custom date here);

Note: I haven't tested this code.

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.