Pages

Sunday, 22 June 2014

Magento Developper’s Guide (Lesson 8) – Rewrite / modify a magento block

This tutorial is the 8th of many , if it’s not already done, i suggest you read to the tutorials starting with the summary of this series.

Sometimes you need to change the behavior of Magento, we want for exemple to change the behavior of a block to display information about a product.

In this tutorial we will see how to change a basic block of Magento. When you want to do this kind of modification, it is better to keep in mind one of the basic rules of magento development

« We never modify the files located in the core »

NEVER…NEVER…NEVER…it’s very important remember forget the idea of ​​going directly edit the files in/app/code/core.

Instead, we will overload this Block, create a class that will extend this core Block and rewrite only the part you want to change. Then, in order to use it, declare your file in our config.xml file (as usual).

 Start by re-creating a module in your folder Easylife and call it MyProduct

So create the file:
/app/code/local/Easylife/Test
With etc/config.xml and do not forget to declare the Easylife_All.xml (see lesson 2 ).

 Create your « modified » Block

What interests us is to rewrite the block Mage_Catalog_Block_Product_View. Let’s say we want to rewrite the method « showInfos » of this Block.

So we will create in /app/code/local/Easylife/Test/Block/Product/file view.php.
Which will contain:

<?php
Class Easylife_Test_Block_Product_View extends Mage_Catalog_Block_Product_View
{
    public function Les_Info()
    {
        return 'les info complementary';
    }
}


Tell Magento to take into account the new version of this block

Edit the config.xml of your module Test and put in it:


<?xml version="1.0"?>
<config>
 <modules>
    <Easylife_Test>
        <version>1.0.0</version>
    </Easylife_Test>
 </modules>
 <global>
   <blocks>
    <catalog>
         <rewrite>
              <product_view>
                    Easylife_Test_Block_Product_View
               </product_view>
             </rewrite>
      </catalog>
  </blocks>
 </global>
</config>
With these tags, we say we will configure a block of Magento’s core called « catalog » and we will rewrite () the « product_view » block of this module.

Now it will take our new block to replace the base.

Conclusion:

You now know to rewrite a block ;)

As usual, feel free to leave your messages and make a comment links to these tutorials on your websites. It’s always nice :)

 Find the summery of this tutorial

No comments:

Post a Comment