Silverstripe Controller Actions
I am trying to add a Controller action to the Page_Controller class via an extension.
The desired result is to be able to navigate to www.mysite.com/setlanguage/spanish
, for example, and update the website language to Spanish via a browser cookie.
However, I'm new to extensions in SilverStripe and so far when I visit the controller action link, all I get is a 404 error.
Please take a look at my code ...
class Page_ControllerLanguageExtension extends Extension {
private static $allowed_actions = array(
'setLanguage'
);
public function setLanguage(SS_HTTPRequest $request) {
$requestedLanguage = $request->param('ID');
$languageCookie = new Cookie;
$languageCookie->set('site_language', $requestedLanguage);
return $this->owner->RedirectBack();
}
}
And I am calling the extension using the YML config file:
Page_Controller:
extensions:
- Page_ControllerLanguageExtension
Thanks in advance.
source to share
So, if you need /setlanguage/<language>
as a URL, you have to route the URL /setlanguage/
to a separate controller:
class SetLanguageController extends Controller {
public function index(SS_HTTPRequest $request) {
$requestedLanguage = $request->param('Language'); //as defined in config below
$languageCookie = new Cookie;
$languageCookie->set('site_language', $requestedLanguage);
return $this->RedirectBack();
}
}
In this case, we don't need to define $allowed_actions
, so this option is enabled by default.
Now in your / mysite / _config / routes.yml you need to define a route to the controller:
---
Name: mysite-routes
After: framework/routes#coreroutes
---
Director:
rules:
'setlanguage/$Language': 'SetLanguageController'
See also: Docs for Routing
source to share