20
Oct
1
Extending $LinkingMode to handle controller actions
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.
The Snippet
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.
Put the new LinkingMode function in your base Page class and you are good to go.
About the Author
Name: Marcus Dalgren
Website: http://www.dragnet.se
Marcus is a web developer currently working at a small startup company called Dragnet in Gothenburg, Sweden. He also does freelance work for small to medium sized businesses in the Gothenburg area.
Comments (1)
-
I used $this->getAction() instead of calling Director::urlParam('Action') to make this work in Silverstripe 2.4 beta.
Posted by Timon, 25/03/2010 8:01am (4 months ago)
RSS feed for comments on this page RSS feed for all comments