Magento2 – Delete Order(s) by CLI Command

Reading Time: 2 minutes

In this article we create a cli command for delete one or more orders.

Sometimes it is necessary to delete one or more orders, because we are wrong with the data or simply because they are test orders.

In magento2 it’s very simple like create a custom command.

Step 1: Define command in di.xml

File: app/code/Magmalabs/HelloWorld/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <type name="Magento\Framework\Console\CommandList">
       <arguments>
           <argument name="commands" xsi:type="array">
              <item name="delete_command" xsi:type="object">Magmalabs\Commands\Console\Command\DeleteCommand</item>
           </argument>
       </arguments>
   </type>
</config>

Step 2: Create command Class

namespace Magmalabs\Commands\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Sales\Model\Order;

class DeleteCommand extends Command
{
  const ID = 'id';
  const DELETE_ALL = 'delete-all';

  private $order;
  protected $orderCollectionFactory;
  protected $registry;

public function __construct(
      \Magento\Framework\App\State $state
  )
  {
      $state->setAreaCode('adminhtml'); // select the environment in which we will work
      $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $this->order = $objectManager->create('\Magento\Sales\Model\Order');
      $this->registry = $objectManager->create('\Magento\Framework\Registry');
      $this->orderCollectionFactory = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
      parent::__construct();
  }

  protected function configure()
  {
      $this
          ->setName('magmalabs:delete')
          ->setDescription('Delete command (Orders)')
          ->addArgument( // declare the input argument
              self::ID,
              InputArgument::OPTIONAL,
              'Id'
          )
          ->addOption( // declare the input option
              self::DELETE_ALL, 'a',
              InputOption::VALUE_NONE,
              'Delete all'
          )
      ;

      parent::configure();
  }

  protected function execute(InputInterface $input, OutputInterface $output)
  {
      $id = $input->getArgument(self::ID);
      $deleteAll = $input->getOption(self::DELETE_ALL);

      if ($deleteAll){
          $this->registry->register('isSecureArea','true'); //  to allow the delete operation
          $orderCollection = $this->orderCollectionFactory->create(); // obtain all orders
          foreach ($orderCollection as $order) {
              $order->delete();
          }
          $this->registry->unregister('isSecureArea');
          $output->writeln('All orders are deleted.');
      }elseif ( $id ){
          $order = $this->order->load($id); // load order by id
          if(empty($order) || !$order->getId()){
              $output->writeln('Order with id ' . $id . ' does not exist.');
          }else{
              $this->registry->register('isSecureArea','true'); //  to allow the delete operation
              $order->delete();
              $this->registry->unregister('isSecureArea');
              $output->writeln('Order with id ' . $id . ' is deleted.');
          }
      }
  }
}
  • – addArgument() method is used to set the argument in command line.
  • – addOption() method is used to set the option in command line.

And it’s done!

Our command will be show here, run the command:

# Delete Order with id = 50
php bin/magento magmalabs:delete 50
#Delete All Orders
php bin/magento magmalabs:delete -a

and response is, as expected:

Case 1: Order with id 50 is deleted.
Case 2: All orders are deleted.

I hope this Magento2 technical note helped you find what you were looking for.

0 Shares:
You May Also Like
Read More

What’s Vtex?

Reading Time: 2 minutesVTEX is one of the best well-known Ecommerce platforms in LATAM because of its exponential growth in the…
Read More

Magento TDD with PHPSpec

Reading Time: 4 minutesToday, we are implementing the MageTest/MageSpec Module based on PHPSpec toolset. In this implementation, we have two different…