Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento: How to create an instance of a block class?

In the core of Magento there is the app\code\core\Mage\Catalog\Block\Product\View\Options.php class for example.

How would I create an instance of that? I tried

Mage::getModel('Mage_Catalog_Block_Product_View_Options');

and it worked, but since this is not a Model class, but a Block class it seems wrong to create it that way. Whats the alternative to that?

Thanks! :)

like image 917
user1638055 Avatar asked Dec 03 '22 02:12

user1638055


2 Answers

Use the createBlock method:

$block = $this->getLayout()->createBlock('catalog/product_view_options')
like image 171
Phil Birnie Avatar answered Jan 17 '23 16:01

Phil Birnie


You need to use createBlock on the Layout, but blocks don't all have a getLayout method.

Mage::app()->getLayout()->createBlock('adminhtml/sales_order_grid');

This is a better technique to "new My_Module_Block_Name" following as it allows for block rewrites in the config.

Defining the blocks in XML, as @Bartosz Górski suggests above, is preferable though it's not possible to directly define diverse dynamic content. Magento has a good solution for this in the Cart's item rendering system - it creates the blocks dynamically but loads their configuration from XML before rendering.

like image 37
Li1t Avatar answered Jan 17 '23 15:01

Li1t