How to override a Magento core block class

Posted on 17. Sep, 2008 by Fido in Design, Development, Magento, Module

This tutorial will show you the proper method for overriding a Mage core class. This will work for Block and Model classes. Controllers are a slightly different story and for another tutorial.

Some discussion on breadcrumbs: I will be overriding the Core file: app/code/core/Mage/Catalog/Block/Breadcrumbs.php (which I will call [Breadcrumbs-B]). This file is not to be confused with the block: app/code/core/Mage/Page/Block/Html/Breadcrumbs.php (which I will call [Breadcrumbs-A]).

[Breadcrumbs-A] contains the notable function ‘addCrumb‘ which adds a crumb to the line of breadcrumbs (to a breadcrumbs array). It can be used many times throughout the site. This file also explicitly uses the page/html/breadcrumbs.phtml file via this line of code in the constructor function: $this->setTemplate(’page/html/breadcrumbs.phtml’);

This block is called from the page.xml layout file (which does not set a template, as this block code sets it’s own template as I just mentioned).

[Breadcrumbs-B] uses [Breadcrumbs-A] via this line of code: $breadcrumbsBlock = $this->getLayout()->getBlock(’breadcrumbs’)

The $breadcrumbs->addCrumb() method is then used to create the crumbs within the block’s _prepareLayout() method.

Confused? Probably. It’s a slightly circular way of using Block code logic and template files.

Anyway, on to the main point of this tutorial: Overriding the breadcrumbs.php block [Breadcrumbs-B]. Why choose this one? Because it controls the layout portion of the breadcrumbs (in conjunction
with the corresponding .phtml file, of course).

The easiest way to override a piece of core code is to simply add it and it’s folder structure to the local folder. We could easily override app/code/core/Mage/Catalog/Block/Breadcrumbs.php by putting it here: app/code/local/Mage/Catalog/Block/Breadcrumbs.php

However, we may want to override it in the true Magento fashion in order to keep our changes truly modular (which of course makes sharing our modules that much easier!)

You may want to do the “easier” method if multiple modules require modification to a Core file, however (to reduce / eliminate conflicts in module code). This tutorial will show you the true override method so we can keep our modules…modular.

So, we will  be creating 3 files (2, if you created my other custom module from my last custom module post and used the same file names)

  • app/code/local/Fido/Catalog/Block/Breadcrumbs.php
  • app/code/local/Fido/Catalog/etc/config.xml
  • app/etc/modules/Fido_All.xml

Step 1

Tell Magento about your new module (app/etc/modules/Fido_All.xml):

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

Step 2

Your config.xml file (app/code/local/Fido/Catalog/etc/config.xml )

<?xml version="1.0"?>
<config>
    <global>
        <blocks>
            <catalog>
                <rewrite>
                    <breadcrumbs>Fido_Catalog_Block_Breadcrumbs</breadcrumbs>
                </rewrite>
            </catalog>
        </blocks>
    </global>
</config>

Notice the tag. Also notice the is on the on line as the name of the class (because of a bug in Magento, there can be no whitespace or return there).

Step 3

Override the block (app/code/local/Fido/Catalog/Block/Breadcrumbs.php)

class Fido_Catalog_Block_Breadcrumbs extends Mage_Catalog_Block_Breadcrumbs  #note: extending file I'm overwriting, not the abstract class the original class extends (is this correct?)
{
protected function _prepareLayout()
{
if ($breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs')) {
/*$breadcrumbsBlock->addCrumb('home',
array('label'=>Mage::helper('catalog')->__('Home'), 'title'=>Mage::helper('catalog')->__('Go to Home Page'), 'link'=>Mage::getBaseUrl())
);*/
//comment the above code out to remove the "home" link from your breadcrumbs.

$title = (string)Mage::getStoreConfig('system/store/name');
$path = Mage::helper('catalog')->getBreadcrumbPath($this->getCategory());
foreach ($path as $name=>$breadcrumb) {
$breadcrumbsBlock->addCrumb($name, $breadcrumb);
$title = $breadcrumb['label'].' '.Mage::getStoreConfig('catalog/seo/title_separator').' '.$title;
}

if ($headBlock = $this->getLayout()->getBlock('head')) {
$headBlock->setTitle($title);
}
}
echo 'yay'; /*The new code just to test if it works! (string appears at the top of the screen if it is) - this should not be left in the code! It's just a method I use to see if Magento is reading the block class at any point.*/
return parent::_prepareLayout();
}

}

I made some comments in the above code so you can see some possible edits.
Another tip: If you are wondering just what file Mage::helper(’catalog’) relates to as I was wondering (there is no ‘catalog.php’ helper file amongst the helpers in the core catalog module) you can add this code in your block to test:

echo get_class(Mage::helper('catalog'));
//outputs Mage_Catalog_Helper_Data

It appears that data.php is a default helper file that Magento searches for. (You would usually use something like Mage::helper(’catalog/data’); )

Tags: , , , , ,

44 Comments

Skeuds

30. Sep, 2008

Hi,

Thank you for this great tutorial, i don’t have the result that i have hope, the breadcrumbs now print for example : Book / Stephen king / Home(the link home appears at the end of the breadcrumbs). Have you any idea to correct it ?

Thank you.

Fido

01. Oct, 2008

What modification did you do exactly? You might want to email me to show me your code (contact section).
What Magento version are you using?

Audrey

01. Oct, 2008

Hi, it works fine for Breadcrumbs, but do you have an idea about navigation ?
I’d like to change the top navigation. I have a lot of subcategories, so it makes a very long list and very long page without anything at the bottom.

Thank you !

Fido

01. Oct, 2008

How do you want to change the top navigation? The files are easy enough to find – there’s a mix of javascript and HTML output in there that complicates things a little (but not too too badly)

Audrey

02. Oct, 2008

For example,
I have 3 categories Books / Press / Publications.
For Books, I have 63 sub categories… So the list in the menu is too long and very easy to use, I have to scroll the page to see the sub categories from nearly 20th sub categorie till the end of the list.

I would like to make like 3 columns with sub categories.

I think I only need to change the function witch create the tree, so I need to rewrite Mage_Catalog_Block_Navigation.

What do you think ?

Fido

02. Oct, 2008

Check out this blog post: http://www.exploremagento.com/magento/editing-the-navigation.php

To see some files that contain code you could use to edit the navigation.

Dinesh

14. Oct, 2008

Hello

How can i call the function of other class of other module from the custom module.

Thanks

Fido

14. Oct, 2008

That depends. You can grab helpers from other modules easily using $this->helper(’module/helperFile’)

Example:
$this->helper(’catalog/product’)->getEmailToFriendUrl($_product);

The getEmailToFriendUrl is defined in the Product.php file in the Catalog module Helper folder.

You can get Models in this way:
$category = Mage::getModel(’catalog/category’)->load($this->getCategoryId());

This code can be used anywhere. This particular code will return a product category object

This is grabbing Category.php from app\code\core\Mage\Catalog\Model

Other useful code snippets to get you on your way:
$layer = Mage::getSingleton(’catalog/layer’);

$categories = Mage::registry(’product’)->getCategoryCollection()
->setPage(1, 1)
->load();

Hope this helps!

[...] and create your own template for over-riding core modules with your custom code, creating your own custom modules and your own template files. Also get jQuery working properly if [...]

JD

27. Jan, 2009

Hi, thanks for the tutorial. The hardest part of this is finding the actual block to override. There seem to be many orphaned bits of code and even with the block hints turned on, setting the rewrite path in the config.xml is a challenge. Any suggestions for tracking that down?

Heikki

10. Feb, 2009

What is the difference between

Mage::getModel

and

Mage::getSingleton
?

[...] Override a Magento Core Module – Magento Custom Module – Magento Development | Explore MagentoThe proper method of over-riding a magento core block. [...]

James Kim

14. Feb, 2009

Great post!
Question. How would you override controller? Or is it possible at all?

Thanks,
James

John

03. Mar, 2009

Hello, this was a great tutorial for me.. I’m having an issue now..

I’m trying to change the Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price class

I made a new class and have it setup.. and it registers.. but I think I have an error in my config.xml file.. I’m not sure how far I need to go with it..

here is a pastebin link to it http://pastebin.com/m70e96997
it will be there for a month..

Please help

shahriat

26. Mar, 2009

It will help me in the future, thanks a lot for ur post such this tutorial :)

ShaheerAL

01. Apr, 2009

Superb post!
This helped me a lot. I am expecting this type of good tutorials for magento in future also.

ShaheerAL

01. Apr, 2009

I am facing a problem here. The link home appears at the end of the breadcrumbs.

For me it has to be Home/JabbaWockeez
Home/RickyMartin

Instead
I am getting JabbaWockeez/Home
RickyMartin/Home

Can you please help me in sorting it out. I have done the changes exactly you instructed.

Skeuds also faced the same problem but solution is not mentioned here.

bboy floorology

22. Apr, 2009

I am trying to Override:

/app/code/core/Payment/Block/Form/Container.php

anybody know the config.xml syntax for it?

bboy floorology

22. Apr, 2009

sorry…I meant:

/app/code/core/Mage/Payment/Block/Form/Container.php

MOinul

11. Jun, 2009

Hello, i tried to override core template block (Mage_Core_Block_Template),
But failed many times. Can you help pls?

Name cnboy

23. Jul, 2009

it is helpful for me!thanks

Phil

25. Jul, 2009

I’d also like to see information about overriding a controller.

Phil

26. Jul, 2009

For overriding controllers, this is helpful: http://www.magentocommerce.com/wiki/how_to_overload_a_controller

Hridaya Ghimire

10. Aug, 2009

Great tutorials..

Thanks for sharing the information.

cheers Hridaya

Yogesh

18. Aug, 2009

hi i have used your code and just tried to change the Home link in bread crumb to Store but in the end after product name or category the home link appears again can you please tell me the solution

Daniel

15. Sep, 2009

Hi there,

thanks for the tutorial!
There’s just one thing that bugs me:
When I call return parent::_prepareLayout(); at the end, the original Core-class will be called and changes I made to the breadcrumb are more or less overridden. If I extend Mage_Core_Block_Template instead this doesn’t happen, of course. Unfortunately this means I will not inherit any other functions from the Core-class and I have to re-implement them, even if I don’t want to make any changes to those functions. Most likely I am doing something wrong here. Any ideas?

Thanks!

Bram

16. Sep, 2009

Hi,

I spent many hours trying to extend the navigation, following your example.
But every time I ended up getting an error!

Now I litteraly copied all of your code in the same folders you did (even used Fido as foldername) and I still get the same error:
Fatal error: Class ‘Fido_Catalog_Block_Breadcrumbs’ not found in /web/christophevdd/studentenmobiel.be/www/app/code/core/Mage/Core/Model/Layout.php on line 462.

I hope you can help me with this :s

adi

13. Oct, 2009

Hey Daniel, i hit the same problem as you did.
You can do a trick, so the only issue that appears in this case is that magento calls the same functions twice ..

First line of your function should be this:
$layoutData = parent::_prepareLayout();
then the rest of the code, and at the end
return $layoutData;

confused

18. Nov, 2009

Thanks for the tutorial, made sense, I thought I knew what was going on until:-

I want to override:

Mage_Adminhtml_Block_Sales_Invoice_Grid

But can’t seem to get the path right in the config.xml file. Nothing that I try seems to work. Have you got any advise on what to try to override a block inside adminhtml? does this make the path different?

Any suggestions you could give would be amazing…

Zoran

28. Jan, 2010

Thanks for the nice explanation.
What is the downside of overriding too many core files, is there an acceptable limit of working modullary by extending the core? Is using events observers methods easier and more flexible way of extending?

DarkGhostHunter

18. Feb, 2010

Note: I’t doesn’t work anymore with Magento 1.4.0

justinjohnson.org

09. Mar, 2010

Thank you so damn much. This worked perfectly for me when overwriting Mage_Catalog_Block_Navigation.

One thing that still alludes me is the meaning in the structure in the etc/config.xml file. Namely, how would I set it up to overwrite Mage_Core_Model_Email_Template? I assume its something like this

My_Core_Model_Email_Template

but where do I put the file? Can it go in the same file that you described in step 2?

Matt

30. Mar, 2010

Nice tutorial. How would you go about overriding Adminhtml/Block/Page.php, but not for all modules, just for one custom module?

Name Paolo

20. Apr, 2010

it’s impossible to override Mage_Core_Block_Template
this seems to be a special class
any ideas?
tell me if anyone can, pls…

jp

20. May, 2010

How do I change the color of the breadcrumbs?

Nikola

21. May, 2010

It does not work in 1.4.1. I guess you can’t overwrite (untested) a block class that is created like this.
$this->getLayout()->createBlock(’catalog/breadcrumbs’);
Mage/Catalog/Block/Category/View.php
Mage/Catalog/Block/Product/View.php

Vitaly

27. May, 2010

It works (!) with Magento 1.4.0.1.

But when I go to “Configuration->Advanced” and set “Disabled” for Fido_Catalog original Breadcrumbs does not appear.
So I can’t swith off this module. Why?..

stef

14. Jun, 2010

great tutorial but if you use Firebug, won’t all make it easier?

anciwasim

23. Jun, 2010

Hello,

If i wanted to override method of continue shopping button, how can i do that.
Location : /app/core/Mage/Checkout/Block/Cart.php
public function getContinueShoppingUrl()
{
$url = $this->getData(’continue_shopping_url’);
if (is_null($url)) {
$url = Mage::getSingleton(’checkout/session’)->getContinueShoppingUrl(true);
if (!$url) {
$url = Mage::getUrl();
}
$this->setData(’continue_shopping_url’, $url);
}
return $url;
}

wookie

10. Aug, 2010

I also had the problem (Magento 1.4.1.1) with the “return parent::_prepareLayout();” creating a “Home” link at the end of the breadcrumb path.

To fix I just extended Mage_Core_Block_Template class instead of Mage_Catalog_Block_Breadcrumbs. Then I added the public function “getTitleSeparator($store = null)” to my new class to keep it working. That way you are using a completely different method instead of inheriting the Mage_Catalog_Block_Breadcrumbs as parent, which adds a “home” link by default.

It is a shame that the [Breadcrumbs-A] script does not support a deleteCrumb method, or for that matter an entire CRUD methdology for manipulating crumbs. ie. Create, Read, Update, Delete. It could be an idea for a module override, but personally I would like to see that type of functionality implemented in the core.

As a side note I note the addCrumb method has a boolean parameter to insert a crumb “$after”, however it is just a parameter in the function and has no influence as it is not actually implemented.

Sandeep Kumar

17. Aug, 2010

Great tutorial on breadcrumbs.I was looking for many days.
Thanks FIDO

Manuel

25. Sep, 2010

Hi, I’m a java developer and i’m studying a Magento framework, it seams that the team did a great work, so I’m trying to understand some meaning and i’ve got some conceptual doubt, for example in Step 2, what is the difference in that code, is instead i’ve got , i mean my block call different shoud it work?
i mean i would like to understand the concept involve in both codes,
thank you for any tips.
Regards.

Name

01. Oct, 2010

the crowd was very big

magento tutorial

31. Dec, 2010

i love you site,it include so many useful sutff.i hope you will keep go on do this

Leave a reply