How to delete Magento product from frontend template code (from view files)

If 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.


2 comments

  1. Hi,
    What about updating prices from frontend.
    I get this error:
    Warning: Invalid argument supplied for foreach() in /var/www/qbien/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 1180

    Do you thinks is possible?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.