Sunday, 22 August 2010

Moving Data around in Magento

Controller to view Like we have seen previously that blocks are separate from the main controller which contains all the data for the view. This helps to reduce coupling of modules and sub modules. Therefore if we supply the block with values it is directly available in the view. Following is an example code snippet on how sending data from main controller to templates / blocks works: $layout = $this->getLayout(); $block = $layout->getBlock('b'); <-- block name b usually given as <modulename> / <block name> $block->setData('variable_name', $value); $block->setData('variable_2', $value2); and so on... and from the template or block simply $this->getData('variable_name'); helps fetch the value. Global If you like to set data which should be available from any module and any module components like model / view / controllers then simply set the data using Magento register / registry as follows: Set: Mage::register('variable_name', 'data'); Get: Mage::registry('variable_name'); Session To move data around session: Get variable: Mage::getSingleton('core/session')->getData('variable_name'); Set variable: Mage::getSingleton('core/session')->setData('variable_name', 'value'); Set variable: Mage::getSingleton('core/session')->setData('variable_name', $value); Parameter Passing Like we always need to send data from views (from some form) back to some controllers for processing or saving data we always need Get or Set and in Magento its simpler to do: Get / Post Data from form(array): $params = $this->getRequest()->getParams(); Data: $params['param_name'];