I'm trying to add a Controller Action to the Page_Controller class via an extension.
The desired result is to be able to go to www.mysite.com/setlanguage/spanish
for instance and have that update the site's language to spanish via a browser cookie.
However I'm failry new to Extensions in SilverStripe and so far when I visit the link to the controller action 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'm calling in the extension with a YML config file:
Page_Controller:
extensions:
- Page_ControllerLanguageExtension
Thanks in advance.
So if you need /setlanguage/<language>
as the url you have to route the url /setlanguage/
to a seperate 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();
}
}
We don't need to define $allowed_actions
in this case, cause action index is allowed by default.
Now in your /mysite/_config/routes.yml you have to define the route to your controller:
---
Name: mysite-routes
After: framework/routes#coreroutes
---
Director:
rules:
'setlanguage/$Language': 'SetLanguageController'
See also: Docs for routing