January 2, 2010

How to delete Magento product from frontend template code

f for some reason (like mine) you need to delete the product from the custom code you placed in lets say view files you might get a bit surprised by the “Cannot complete this operation from non-admin area.” error. Here is a little trick on how to pass behind this.
Here is the working sample code part:

$_authors_product = new Mage_Catalog_Model_Product();
 $_authors_product->load($_item_val_id);
 
 //echo "DELETED... ".$_POST['submit_item4sale_remove_by_entity_id'];
 $_item_val_id = $_POST['submit_item4sale_remove_by_entity_id']; 
 $_item_val_id = (int)str_replace('entity_id_', '', $_item_val_id);
 
 $_authors_product = new Mage_Catalog_Model_Product();
 $_authors_product->load($_item_val_id);
 
 $_current_customer_id = Mage::getSingleton('customer/session')->getCustomer()->getId();
 
 //Allow deletion only if product is from author
 if($_authors_product->submited_by_author == $_current_customer_id) 
 {
  //var_dump(Mage::registry('isSecureArea'));
 
  Mage::register('isSecureArea', true);
  //$_authors_product->delete();
  echo 'ALLOWED DELETED OH YEAAAAAA....';
  Mage::unregister('isSecureArea'); 
 }
 
 
The above code is part of a code extracted form a project I am working on these days. The important stuff is the following part:

Mage::register('isSecureArea', true);
echo 'ALLOWED DELETED OH YEAAAAAA....';
Mage::unregister('isSecureArea');
 
 
Basically the idea is to write the appropriate value in registry, Mage::register(‘isSecureArea’, true);, and remove it once we delete our product.

6 comments: