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

Mage::getModel('catalog/product')

 

Adding a block to the layout from withing the controller

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

 

Getting a parameter from the url

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

 

Get the current logged in user

Mage::getSingleton('customer/session')->getCustomer()->getId();

 

Get the store email address from the config

 Mage::getStoreConfig('trans_email/ident_sales/email')

 

Get the store phone number from the config

Mage::getStoreConfig('general/store_information/phone')

 

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 *