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

Magento 2

Magento 2 allows you to manage order statuses and states dynamically. In this tutorial, we will learn how to create a new order status programmatically using a Data Patch. We will add a new order status processing_review and assign it to the processing state.

Steps to Create a Custom Order Status in Magento 2

1. Create a Data Patch File

We need to create a Data Patch file to install the new order status. Navigate to your module’s Setup/Patch/Data/ directory and create a new PHP file named AddOrderStatus.php.

File Path: app/code/WebChandra/OrderStatus/Setup/Patch/Data/AddOrderStatus.php

<?php
declare(strict_types=1);

namespace WebChandra\OrderStatus\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Sales\Model\Order\StatusFactory;
use Magento\Sales\Model\ResourceModel\Order\StatusFactory as StatusResourceFactory;

class AddOrderStatus implements DataPatchInterface
{
    public function __construct(
        private readonly ModuleDataSetupInterface $moduleDataSetup,
        private readonly StatusFactory            $statusFactory,
        private readonly StatusResourceFactory    $statusResourceFactory
    ) {
    }

    /**
     * Apply Data Patch to add new Order Status and State.
     * @return void
     * @throws \Exception
     */
    public function apply(): void
    {
        $this->moduleDataSetup->startSetup();

        $statusResource = $this->statusResourceFactory->create();
        $status = $this->statusFactory->create();

        try {
            $status->setData([
                'status' => 'processing_review',
                'label' => 'Order Review'
            ]);
            $statusResource->save($status);
            
            $status->assignState('processing', true, true);
        } catch (\Exception $exception) {
            throw new $exception;
        }

        $this->moduleDataSetup->endSetup();
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}

2. Run Setup Upgrade Command

Once the Data Patch file is created, run the following command to apply the patch:

php bin/magento setup:upgrade

3. Verify the New Order Status

After running the upgrade command, navigate to the Magento 2 Admin Panel:

Admin Panel Path:

Stores -> Settings -> Order Status

You should see the new status Order Review assigned under the Processing state.

Conclusion

Using the above method, you can easily create a new order status and assign it to a specific state programmatically in Magento 2. This approach ensures that your custom order status is properly integrated into your Magento store without manual intervention.