Friday, 8 November 2019

Add order state and status programmatically in Magento 2.3 using Data Patch

1.Create file registration.php in app/code/Custom/OrderStatus/registration.php

<?php
/**
 * Ansar Husain
 * Custom_OrderStatus
 */
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Custom_OrderStatus',
    __DIR__
);





2. Create file module.xml app/code/Custom/OrderStatus/etc/module.xml


<?xml version="1.0"?>
<!--
/**
* Ansar Husain
* Custom_OrderStatus
**/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Custom_OrderStatus" />
</config>

3. Create file AddNewOrderStatus.php app/code/Custom/OrderStatus/Setup/Patch/Data/AddNewOrderStatus.php

<?php

namespace Custom\OrderStatus\Patch\Data;

use Magento\Sales\Setup\SalesSetupFactory;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;

class AddNewOrderStatus implements DataPatchInterface , PatchVersionInterface
{
    protected $_moduleDataSetup;
    protected $_salesSetupFactory;

    public function __construct(ModuleDataSetupInterface $moduleDataSetup , SalesSetupFactory $salesSetupFactory)
    {
        $this->_moduleDataSetup = $moduleDataSetup;
        $this->_salesSetupFactory = $salesSetupFactory;

    }

    public function apply()
    {
        $salesSetup = $this->_salesSetupFactory->create(['setup'=>$this->_moduleDataSetup]);

        $salesSetup->installEntities();

        $data[] = ['status' => 'my_custom_status', 'label' => 'My Custom Status'];
        $this->_moduleDataSetup->getConnection()->insertArray(
          $this->_moduleDataSetup->getTable('sales_order_status'),['status','label'],$data
        );

        $data2[] = ['status' => 'my_custom_status', 'state' => 'my_custom_status_state','is_default'=>0];
        $this->_moduleDataSetup->getConnection()->insertArray(
           $this->_moduleDataSetup->getTable('sales_order_status_state'),['status','state','is_default'],$data2
        );
        // TODO: Implement apply() method.
    }
    public function getAliases()
    {
        return [];
        // TODO: Implement getAliases() method.
    }
    public static function getVersion()
    {
        return '2.3.2';
        // TODO: Implement getVersion() method.
    }
    public static function getDependencies()
    {
        return [];
        // TODO: Implement getDependencies() method.
    }

}






No comments:

Post a Comment