How To

How to Create Custom Order Status and State Programmatically in Magento 2

Hello, Magento pals,

Today we are going to learn how you can create custom order status and state programmatically in default Magento2. So, let’s get started.

Every order has an order status, which is coupled with the order processing workflow stream. The position of an order in the workflow is described by the state. In default Magento store, order status, and order state settings are already defined. So, you can see all the order statues in your Back-end.

To see all the order status, use the below admin configuration tab,

Store > Settings > Order Status.

But often time, we have the need to create our custom order status and state. And today, we are going to figure out how to create order status and state programmatically in default Magento 2.

1. The first thing you should do is to create a file named “Registration.php” in extension. Create the file at app\code\Vendor\Extension\ with the following code.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Extension',
    __DIR__
);

2. After creating the above file with the code, now create the “Module.xml” file in etc folder of extension at this path, app\code\Vendor\Extension\etc\ with the following code.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Extension" setup_version="1.0.0" schema_version="1.0.0">
    </module>
</config>

3.Now, create a file named “InstallData.php” in the setup folder of the extension. Create the file at,                       app\code\Vendor\Extension\Setup\ with the following code.

<?php

namespace Vendor\Extension\Setup;

use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Sales\Model\Order\StatusFactory;
use Magento\Sales\Model\ResourceModel\Order\StatusFactory as StatusResourceFactory;

class InstallData implements InstallDataInterface
{
    /* 
        CUSTOM_STATUS_CODE,CUSTOM_STATE_CODE and CUSTOM_STATUS_LABEL
    */
    const CUSTOM_STATUS_CODE = 'custom_status';
    const CUSTOM_STATE_CODE = 'custom_state';
    const CUSTOM_STATUS_LABEL = 'Custom Status';

    protected $statusFactory;
    protected $statusResourceFactory;

    public function __construct(
        StatusFactory $statusFactory,
        StatusResourceFactory $statusResourceFactory
    ) {
        $this->statusFactory = $statusFactory;
        $this->statusResourceFactory = $statusResourceFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $this->addCustomOrderStatus();
    }

    protected function addCustomOrderStatus()
    {
        $statusResource = $this->statusResourceFactory->create();
        $status = $this->statusFactory->create();
        $status->setData([
            'status' => self::CUSTOM_STATUS_CODE,
            'label' => self::CUSTOM_STATUS_LABEL,
        ]);
        try {
            $statusResource->save($status);
        } catch (AlreadyExistsException $exception) {
            return;
        }
        $status->assignState(self::CUSTOM_STATE_CODE, true, true);
    }
}

As you have noticed, the addCustomOrderStatus() method performs two steps. One, it will make a new customized order status and will save it so it can appear in the database of sales_order_status. And second, by adding a new database record in sales_order_status_state, it will link the created status to the order state.

Because there is no other database table available for order state, each unique value is considered as a separate order state in the state column of sales_order_status_state.

Now, to activate the module and execute the setup script, run the below setup upgrade commands,

php bin/magento setup:upgrade

Check Stores -> Settings -> Order Status.

So, today we learned how you can successfully create order status and state in default Magento 2. You can customize the code as per your need for fetching data. Let us know if you had any problems while implementing the code.

If you liked this article, then give it a thumbs-up and share your reviews in the comments below. Also, share this with your Magento colleagues and friends.

Lastly, if you want us to write on a topic, then give your suggestions in comments. In case you need Any help,We will be happy to help you ?

 

Click to rate this post!
[Total: 6 Average: 4.8]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

7 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago