Part-2 : Create Order Status Programmatically
In the Previous Blog we created order status manually through admin . No in this blog we will create the same status using code.
We will create the order status using upgrade schema , the advantage of using schema over manual way is that you don not need to re create statuses .
It will generate the statuses with setup upgrade command .
Like any other module we need to create registration.php and module.xml files to register our module . Create these file if they are not created.
Once you have created these files we will create new order status using upgrade schema.
Create UpgradeSchema.php file in Vendor/Module/Setup folder in my case Gm is Vendor and Module is my Module name. Once You create the upgrade schema paste the below code in there.
<?php namespace Gm\Module\Setup; use Magento\Framework\Setup\UpgradeSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\StatusFactory; use Magento\Sales\Model\ResourceModel\Order\StatusFactory as StatusResourceFactory; class UpgradeSchema implements UpgradeSchemaInterface { const CUSTOM_STATUS_CODE = 'order_verified'; const CUSTOM_STATUS_LABEL = 'Order Verified'; public function __construct( StatusFactory $statusFactory, StatusResourceFactory $statusResourceFactory ) { $this->statusFactory = $statusFactory; $this->statusResourceFactory = $statusResourceFactory; } public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $installer = $setup; $installer->startSetup(); if (version_compare($context->getVersion(), '1.0.1') < 0) { $this->addCustomOrderStatusFull(); } $setup->endSetup(); } protected function addCustomOrderStatusFull() { $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(Order::STATE_PROCESSING, false, true); } }
In the above code replace 1.0.1
with your module version given in module.xml
.
I have added the custom status code order_verified
you can add your custom code and replace the label with your custom label .
Once the code Is Added run the setup upgrade and you will be able to see the newly created status in order statuses.