Rewrite a native magento block

Sometimes we need to change the default behaviour of Magento, such as changing the behavior of a block to display a little more information than now. In this tutorial we will see how to change a native magento block.
When one wants to do this kind of change, it is better to keep in mind one of the basic rules of magento development (careful if I make an exam... it will fall !! xD):


DO NOT change the core of magento.... NEVER .

Forget the idea of directly editing the files in /app/code/core.

Instead, we will override the Block you want to change. So create a class which extend the core Block and rewrite only the part you want to change . Then, to be able to use it declare our new class in the config.xml

1- Start by recreating a module in your Pfay folder named MyProduct

So create the folder: /app/code/local/Pfay/MyProduct With etc/config.xml file and be sure to first create the file Pfay_Myproduct.xml in app/etc/modules/.

2- Create the "modified" block

What interests us is to rewrite the block Mage_Catalog_Block_Product_View . We want to rewrite the method hasRequiredOptions to always returns TRUE. So we will create in /app/code/local/Pfay/MyProduct/Block/Product/ a View.php . Which will contain:

class Pfay_Myproduct_Block_Product_View extends Mage_Catalog_Block_Product_View
{
    /**
     * Check if product has required options
     *
     * @return bool
     */
    public function hasRequiredOptions()
    {
        return true;
    }
}

Note that our new block is actually defined as usual when we create a block except that extend this one extends : Mage_Catalog_Block_Product_View

3- Tell Magento to consider the new version of the Block

Edit the config.xml of your module MyProduct like this:

<?xml version="1.0"?>
<config>
 <modules>
    <Pfay_Myproduct>
        <version>1.0.0</version>
    </Pfay_MonProduit>
 </modules>

<global>
   <blocks>
    <catalog>
         <rewrite>
              <product_view>Pfay_Myproduct_Block_Catalog_Product_View</product_view>
             </rewrite>
      </catalog>
  </blocks>
 </global>
</config>

With these tags, you tell Magento that the block whith the code for "catalog/product_view" (Mage_Catalog_Block_Product_View) will be replaced by Pfay_Myproduct_Block_Catalog_Product_View. He will then take our new Block instead of the native one.

The behavior of our method is changed but we do not lose the other methods of the block thanks to the extends of the native magento block. Conclusion:
There you go ! You know now how to rewrite a block ;) As usual, feel free to ask questions and if that does not work for you download the code to compare it with yours.
Available documents for this article :
Books that can help you :
  • Livre Magento Developer's Guide by Alan Mc Gregor
  • Livre Magento Performance Optimization
  • Livre Grokking Magento Vinai
Questions about this lesson
No questions for this lesson. Be the first !

You must be logged in to ask for help on a lesson.