Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Customising the CMS /

How to insert new code into a pre-existing function using Page.php


Reply


3 Posts   1093 Views

Avatar
WebSiteGuy

Community Member, 8 Posts

6 December 2010 at 7:31am

Edited: 06/12/2010 7:31am

I have successfully altered my SiteTree.php to add a metarobots tag by inserting the following into the MetaTags function it uses:

      //custom-code: BOF Metarobot tags - Create and insert the meta robots tag
      if($this->MetaRobotsTag) {
         $tags .= "<meta name=\"robots\" content=\"" . Convert::raw2att($this->MetaRobotsTag) . "\" />\n";
      }
      //custom-code: EOF Metarobot tags - Create and insert the meta robots tag

This uses a new DropdownField called MetaRobotsTag, which I added to mysite/code/page.php using addFieldToTab for Root.Content.Metadata.

I'd like to know, is there a way I could have added the code I included above into the SiteTree.php MetaTags function without directly editing SiteTree.php. My guess is that I somehow could have extended the SiteTree.php MetaTags function in mysite/code/Page.php , but I can't figure out how to add a line to a pre-existing function. I understand a new class would add an entire new functionality. In this case I just need to add one line. Can anyone please suggest the cleanest way to do this, or was editing SiteTree.php the only way.

Please excuse if any of the above is a "dumb" question, I'm just learning SS and haven't gotten my head around all the different approaches to extending it.

Avatar
WebSiteGuy

Community Member, 8 Posts

6 December 2010 at 7:58am

OK, I copied the entire MetaTags function from sapphire/core/model/SiteTree.php into my class Page extends SiteTree in mysite/code/Page.php file and that works. It is however a bit overkill since I just needed to add one line to that function. Is there a way of appending my one line to the function without having to duplicate the entire function in Page.php?

Avatar
Willr

Forum Moderator, 5513 Posts

6 December 2010 at 8:12pm

Note the line at the bottom of the function in SiteTree

$this->extend('MetaTags', $tags);

This means that you can define a 'function MetaTags($tags) {}' on an extension and if you add that extension to the SiteTree it will call your function at the end of the SiteTree tree function - allowing you to change the value of $tags. So simply create an extension, define that function
to append it to $tags.

http://doc.silverstripe.org/dataobjectdecorator