Magento2 Orders – How to Create a New Order Status/State in Magento 2 Module

magento2magento2.1.6moduleorders

I'd like to create a new order state like processing, complete and etc.. Using my custom module (without using the admin panel).

How can I do that?

Thanks

Best Answer

In the block, controller or model of your custom module

<?php

namespace Custom\Module\Block\Path;

class Sample
extends \Magento\Framework\View\Element\Template implements \Magento\Framework\View\Element\BlockInterface
{
    protected $status;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Sales\Model\Order\Status $status,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->status = $status;
    }

    public function setCustomStatus(){
        // create status
        $this->status->setData('status', 'your_status') //code
             ->setData('label', 'Your New Status') //title
             ->save();

        // assign your state in to Magento order states
        $this->status->assignState(\Magento\Sales\Model\Order::STATE_NEW, true);
    }

}

Here is the list of Magento order states, which is found in file \Magento\Sales\Model\Order

const STATE_NEW = 'new';

const STATE_PENDING_PAYMENT = 'pending_payment';

const STATE_PROCESSING = 'processing';

const STATE_COMPLETE = 'complete';

const STATE_CLOSED = 'closed';

const STATE_CANCELED = 'canceled';

const STATE_HOLDED = 'holded';

const STATE_PAYMENT_REVIEW = 'payment_review';