Delete operation is forbidden for current area
Agree with Max that you should use the ProductRepositoryInterface::deleteById($sku)
, but you'll also need to make an additional change to get permissions to delete.
Note that the Admin area handles this by creating the following config in app/code/Magento/Backend/etc/adminhtml/di.xml
<preference for="Magento\Framework\Model\ActionValidator\RemoveAction" type="Magento\Framework\Model\ActionValidator\RemoveAction\Allowed" />
The Magento\Framework\Model\ActionValidator\RemoveAction\Allowed
class prevents a permission check by simply returning true
in the isAllowed
method.
Without the above change to di.xml the Magento\Framework\Model\ActionValidator\RemoveAction
class will be used, which will cause your delete request to fail unless $this->registry->registry('isSecureArea')
is set to true.
It looks like you are trying to create some console commands and I'm not very familiar with them yet, so your best bet for now may be to set the registry to allow the delete operation and refactor later if a cleaner solution is found.
$this->registry->register('isSecureArea', true)
I recently had this problem while writing a console command to delete empty categories.
As said in another answer you need to register 'isSecureArea'
to true.
To do this in a console command you need to have the Magento\Framework\Registry class passed into your constructor.
In my case I did in this way:
public function __construct(CategoryManagementInterface $categoryManagementInterface, CategoryRepositoryInterface $categoryRepositoryInterface, Registry $registry)
{
$this->_categoryRepository = $categoryRepositoryInterface;
$this->_categoryManagement = $categoryManagementInterface;
$registry->register('isSecureArea', true);
parent::__construct();
}
and then in the execute
method I used the repository to perform the actual deletion:
$this->_categoryRepository->deleteByIdentifier($category->getId());
if you using script please create the registry object as shown below.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get('Magento\Framework\Registry')->register('isSecureArea', true);
Please click here for detailed explanation. http://www.pearlbells.co.uk/mass-delete-magento-2-categories-programmatically/
if it is a one time script, you can use OM