1

Version: Magento 2.1.0

I run the following codes in my controller and got error:

$customer = $this->customerFactory->create()->load($id);
$customer->delete();

Error:

Exception #0 (Magento\Framework\Exception\LocalizedException): Delete operation is forbidden for current area

My code was stopped by the beforeDelete() method in Magento\Framework\Model\AbstractModel.php. It calls another method called isAllowed(AbstractModel $model)

How do I bypass these methods and delete a customer?

1 Answer 1

7

Customer delete operation is valid from admin only. When you perform delete operation, magento check isSecureArea is true/false. So you can assign isSecureArea by following way:

/**
 * @var \Magento\Framework\Registry
 */
protected $registry;

/**
 * @param Context $context
 * @param PageFactory $resultPageFactory
 */
public function __construct(
    \Magento\Framework\Registry $registry
) {
    $this->registry = $registry;
}

Now change your code following way:

$this->registry->register('isSecureArea', true);
$customer = $this->customerFactory->create()->load($id);
$customer->delete();

Clear cache.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.