Magento 2 – delete objects
In this tutorial I show you how to delete objects in Magento 2. You may discovered a “Delete operation is forbidden for current area” error message if you want to call a delete function. It is a bit tricky to delete things in Magento, but if you know how, it is very easy.
Magento 2 – delete objects
You can delete a loaded object by calling its delete() function:
1 | $object->delete(); |
Magento 2 defines areas for optimizing request processing. Depending from where you call your code, you are in a different area. That is a fact you may not know, it is not that important. Important is, that you need to declare your area as secure area. This is mandatory for deleting objects. It sounds difficult, but it is very easy. Look at the following lines of code. We load a customer object by collection and if it is found, we delete it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class DeleteCustomer { protected $_customerFactory; protected $_registry; public function __construct(\Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Framework\Registry $registry ) { $this->_logger = $logger; $this->_helper = $helper->create(); $this->_customerFactory = $customerFactory; $this->_registry = $registry; } $collection = $this->_customerFactory->create()->getCollection()->addAttributeToSelect('*') ->addAttributeToFilter('entity_id', array('eq' => 3)); $collection->load(); $customer = null; if($collection->getSize() == 1) { $this->_registry->register('isSecureArea', true); $customer->delete(); echo "customer deleted\n"; } else { echo "no customer found\n"; } } |
We only need to call $this->_registry->register(‘isSecureArea’, true); This makes your current area a secure area. For this you need a registry object, which is injected to this class and is injected from \Magento\Framework\Registry. That is all you need to know about it.
What else?
You can use the same structure to delete all other loaded objects like orders, products or event custom objects. You only need to load them first, by sku, id, or any other attribute. For custom attributes you may use a collection for this. You may also use a filtered collection to mass delete things. Deleted objects are irretrievably deleted, so watch out! Do a database backup before experimenting and test your code on a development system first!
Conclusion
I showed you how to programmatically delete objects in Magento 2. With this code in mind, you can build nice modules.