Magento 2 – How to Create New Order Status and Make It Visible on Frontend

magento2order-status

I have created a new order status and assign it to processing state:

UpgradeSchema.php

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{

    public function upgrade(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;
        $installer->startSetup(); 

        if (version_compare($context->getVersion(), "1.0.1", "<")) {
          $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
          $status = $objectManager->create('Magento\Sales\Model\Order\Status');
          $status->setData('status', 'delivery_pending')->setData('label', 'Delivery Pending')->save();
          $status->assignState(\Magento\Sales\Model\Order::STATE_PROCESSING, true);
        }
        $setup->endSetup();
    }
}

The problem is when the order of my new order status won't show at frontend and when I check at admin page in order status configuration, the new order status is not visible on storefront

example

Best Answer

In your code you need to replace this statement with following.

$status->assignState(\Magento\Sales\Model\Order::STATE_PROCESSING, true);

Replace with

$status->assignState(\Magento\Sales\Model\Order::STATE_PROCESSING, true, true);

Even you can try the alternative for setup script.

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{

    public function upgrade(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;
        $installer->startSetup(); 

        if (version_compare($context->getVersion(), "1.0.1", "<")) {
          $data[] = ['status' => 'delivery_pending', 'label' => 'Delivery Pending'];
          $setup->getConnection()->insertArray($setup->getTable('sales_order_status'), ['status', 'label'], $data);
          $setup->getConnection()->insertArray(
            $setup->getTable('sales_order_status_state'),
            ['status', 'state', 'is_default','visible_on_front'],
            ['delivery_pending','processing','0',1]
         );
        }
        $setup->endSetup();
    }
}
Related Topic