I want to create command for delete operation for simple product by sku. I'm getting following error.how to set admin area?
[Magento\Framework\Exception\LocalizedException]
Delete operation is forbidden for current area
<?php
namespace Sivakumar\Sample\Console;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
class DeleteSimpleProduct extends Command
{
protected $_product;
public function __construct(\Magento\Catalog\Model\Product $_product)
{
$this->_product =$_product;
parent::__construct();
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName('delete_simple_product')
->setDescription('Delete Simple Product')
->setDefinition($this->getOptionsList());
parent::configure();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$errors = $this->validate($input);
if ($errors) {
throw new \InvalidArgumentException(implode("\n", $errors));
}
$product_id = $this->_product->getIdBySku($input->getOption('sku'));
$product=$this->_product->load($product_id);
$product->delete();
$output->writeln('<info>product deleted ' . $input->getOption('sku') . '</info>');
}
public function getOptionsList()
{
return [
new InputOption('sku', null, InputOption::VALUE_REQUIRED, 'SKU'),
];
}
public function validate(InputInterface $input)
{
$errors = [];
$required =['sku',];
foreach ($required as $key) {
if (!$input->getOption($key)) {
$errors[] = 'Missing option ' . $key;
}
}
return $errors;
}
}
di.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Console\CommandList">
<arguments>
<argument name="commands" xsi:type="array">
<item name="delete_simple_product" xsi:type="object">Sivakumar\Sample\Console\DeleteSimpleProduct</item>
</argument>
</arguments>
</type>
</config>