Magento2 Extensions – Creating New Order States Programmatically

extensionsmagento2order-stateorder-statusplugin

I'm stuck on trying to create a new order state programmatically.
So far I'm only able to read the currently available states from

\Magento\Sales\Model\Config\Source\Order\Status

I am unable to find a model I can fill let alone some kind of interface, api or Manager for order states.

In magento 1.9 this was done using the following code:

model = Mage::getModel('sales/order_status')->load('error');
$model->setStatus('error');
$model->setLabel('Not Sent To XXX');
$model->save();
$model->assignState(Mage_Sales_Model_Order::STATE_HOLDED, false);

Best Answer

We should take a look some tests:

dev/tests/integration/testsuite/Magento/Payment/_files/order_status.php

/** @var \Magento\Sales\Model\Order\Status $status */
$status = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order\Status');
//status for state new
$status->setData('status', 'custom_new_status')->setData('label', 'Test Status')->save();
$status->assignState(\Magento\Sales\Model\Order::STATE_NEW, true);
//status for state canceled
$status->setData('status', 'custom_canceled_status')->setData('label', 'Test Status')->unsetData('id')->save();
$status->assignState(\Magento\Sales\Model\Order::STATE_CANCELED, true);

We can use Object Manager or inject Magento\Sales\Model\Order\Status in the constructor.

Related Topic