What are the cases in which $this from a custom theme's template does not recognize the theme's appropriate block?

magento.stackexchange https://magento.stackexchange.com/questions/167431

Question

Pardon me for my lack of Magento knowledge in advance. I'm adding custom functionality to a theme like this:

app/code/local/Myvendor/Mymodule/Block/Catalog/Product/View.php:

class Myvendor_Mymodule_Block_Catalog_Product_View extends Mage_Catalog_Block_Product_View
{
  public function myCustomFunction() {
    // Custom functionality
  }
}

This function is called in a template like this:

app/design/frontend/myvendor_mymodule/default/template/catalog/product/view/options/wrapper.phtml

<?php echo $this->myCustomFunction(); ?>

However, in Xdebug, $this always points to Mage_Catalog_Block_Product_View

What are the cases in which the custom module's block is not recognized, and $this defaults to the Mage block instead?

  • The custom module is active at app/etc/modules/Myvendor_Mymodule.xml
  • The custom block is specified at app/code/local/Myvendor/Mymodule/etc/config.xml: <blocks> <myvendor_mymodule> <class>Myvendor_Mymodule_Block</class> </myvendor_mymodule> </blocks>

  • The public function name does not conflict with any other function names.

  • It's necessary for the template to be located inside the myvendor_mymodule package.
Was it helpful?

Solution

You need to rewrite Mage_Catalog_Block_Product_View class, then you can use this way

<?php echo $this->myCustomFunction(); ?>
<blocks>
    <myvendor_mymodule>
        <class>Myvendor_Mymodule_Block</class>
    </myvendor_mymodule>
    <catalog>
        <rewrite>
            <product_view>Myvendor_Mymodule_Block_Catalog_Product_View</product_view>
        </rewrite>
    </catalog>
</blocks>

Clear cache.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top