Useful Magento code snippets

So I have been playing around with Magento for a couple of weeks and I have come across some very useful code snippets along the way. I have listed them below in the hope that they are useful to me and anybody else in the future. I will be adding more as I come across them. Let me know in the comments if you come across any more!

Redirect or force 404 not found

return $this->_forward('defaultNoRoute');


Get a model



Adding a block to the layout from withing the controller

$block = $this->getLayout()->createBlock('rewardpoints/rewards_viewCat','test',array('template'=>'rewardpoints/rewards/viewCat.phtml','category_id'=>$cat_id));


Getting a parameter from the url

$id =$this->getRequest()->getParam('id');


Get the current logged in user



Get the store email address from the config



Get the store phone number from the config



Not strictly magento, but still useful; format price

echo number_format($_product->getFinalPrice(),2,'.',',');


Get a Block to use its functions from anywhere

$block = Mage::getBlockSingleton('checkout/cart_sidebar');


Get the basket sub total, anywhere

$block = Mage::getBlockSingleton('checkout/cart_sidebar');
echo Mage::helper('checkout')->formatPrice($block->getSubtotal());

Reset / Unset all children of a block

<reference name="right">
    <action method="unsetChildren"></action>
<reference name="right">


Leave a Reply

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