Snippets - Little bits of code to make you happy
Extending $LinkingMode to handle controller actions
Tweet20 October 2009 | |
As some of you might have noticed, as soon as you step outside of the standard SiteTree structure you're pretty much on your own. Today I had to make a menu that mixed normal SiteTree pages and controller actions.
I wanted to be able to use LinkingMode to check if this is the currently viewed page and unfortunately the standard function does not take controller actions into account.
Add this to your Controller Class:
public function LinkingMode($action = null) {
$controllerAction = $this->getAction();
if (is_null($controllerAction) && is_null($action))
return parent::LinkingMode();
if ($action == $controllerAction)
return 'current';
else
return $this->LinkOrSection();
}
What it does
First of all we give the LinkingMode an optional parameter called $action which is set to null by default. Director::urlParam('Action') will return null if you are on the default or index action so if urlParam is null and no action has been given we simply return the results from the original LinkingMode function.
However if an action is entered into the function it checks whether this action matches the urlParam. If it does it returns current, otherwise we return the results from the LinkOrSection function. This means that the controller which the action resides in will get the class section if it's in the same menu as the action.
Use Case
Below is an example of how to use the snippet in your templates. The Link function accepts an optional action parameter which will return the appropriate url for a controller action. As you can see, the new LinkingMode function works the same way. Note that if you're outputting a normal menu no parameter should be passed.
<% control Menu(1) %> <a href="$Link" class="$LinkingMode">$MenuTitle</a> <% end_control %> <a href="$Link(blog)" class="$LinkingMode(blog)">Blog</a>
Put the new LinkingMode function in your base Page class and you are good to go.
2 Comments
RSS feed for comments on this page RSS feed for all comments
moloko_man
13/08/2011 5:30am (2 years ago)
I realize this is an older post... but here goes anyways.
I understand how this works in a Page_controller, but what about DataObjects?
I have a DataObject that is being pulled into page with the show function and having it rendered on its own page. Is there a way to have the dataobject have its on LinkingMode?
moloko_man
13/08/2011 5:33am (2 years ago)
I guess I'm up way past my bed time, I just found a solution in a later article here: http://www.ssbits.com/tutorials/2010/dataobjects-as-pages-part-1-keeping-it-simple/
Thanks for all the awesome articles.
Post a comment ...
You cannot post comments until you have logged in. Login Here.