4

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! :)

user1638055
  • 482
  • 2
  • 8
  • 24

3 Answers3

17

Use the createBlock method:

$block = $this->getLayout()->createBlock('catalog/product_view_options')
Phil Birnie
  • 1,104
  • 2
  • 12
  • 29
  • While this method works, it's best to create blocks in xml files and display them in template files using the getChildHtml() method. It's more flexible this way - allows replacing blocks when needed or removing them entirely in other xml files. – Bartosz Górski Sep 09 '14 at 18:55
4

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.

Li1t
  • 622
  • 6
  • 16
-4

Just use new Operator

$block = new Mage_Catalog_Block_Product_View_Options();

as the classes will be autoloaded when you request them !

Meabed
  • 3,828
  • 1
  • 27
  • 37
  • 9
    Don't do that. What if I want to rewrite that block?! See @PhilB's reply. **That's** how you should do it. – nevvermind Nov 07 '13 at 10:33