Friday 18 November 2016

How will you override Block/Model/controllers in Magento?

After spending many hours in rewriting block and controller of Magento core module, I finally came up with a solution.

Here I am going to rewrite block: Mage/Adminhtml/Block/Sales/Shipment/Grid.php
and controller: Mage/Adminhtml/controllers/Sales/ShipmentController.php
First you will need to make a xml file for your new module at app/etc/modules directory
CompanyName_Adminhtml.xml

<?xml version="1.0"?>
<config>
    <modules>
        <CompanyName_Adminhtml>
            <active>true</active>
            <codePool>local</codePool>
        </CompanyName_Adminhtml>
    </modules>
</config>

Then, make folders in your app/code/local directory as follows:

- CompanyName
-> Block
—> Sales
—-> Shipment
——> Grid.php
-> controllers
—> Sales
—-> ShipmentController.php
-> etc
—> config.xml

In etc/config.xml, your code should look like below:


<?xml version="1.0"?>
<config>
    <modules>
        <CompanyName_Adminhtml>
            <version>0.1.0</version>
        </CompanyName_Adminhtml>
    </modules>

    <global>
    <blocks>
        <adminhtml>
            <rewrite>
             
<sales_shipment_grid>CompanyName_Adminhtml_Block_Sales_Shipment_Grid</sales_shipment_grid>
            </rewrite>
        </adminhtml>
    </blocks>

    <routers>
            <adminhtml>
           <rewrite>
                  <sales_shipment>
                      <from><![CDATA[#^/admin/sales_shipment/$#]]></from>
                      <to>/admin/sales_shipment/</to>
                  </sales_shipment>
            </rewrite>
       </adminhtml>
        </routers>
   </global>


    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <CompanyName_Adminhtml before="Mage_Adminhtml">CompanyName_Adminhtml</CompanyName_Adminhtml>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>

</config>


In ShipmentController.php, you should start like this:

require_once("Mage/Adminhtml/controllers/Sales/ShipmentController.php");
class CompanyName_Adminhtml_Sales_ShipmentController extends Mage_Adminhtml_Sales_ShipmentController
{
  //controller methods goes here..
}

require_once is necessary as magento is not going to load controllers as it does for blocks and models.

In block Grid.php, start the file like below:

class CompanyName_Adminhtml_Block_Sales_Shipment_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
  // block methods goes here..
}

That’s it! Now you should get your local Grid.php and ShipmentController.php loading instead of core’s

No comments:

Post a Comment