alex
alex

Reputation: 307

Can I dynamically change SilverStripe theme?

I have made for my site additional theme for cecutients (people with low eyesight). Can I dynamically change site theme pushing some button on the main page?

Upvotes: 4

Views: 519

Answers (2)

Luis Dias
Luis Dias

Reputation: 1

An update for Silverstripe 4.x version:

use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\Control\Session;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\View\SSViewer;
use SilverStripe\Core\Config\Config;

class PageController extends ContentController
{

    private static $allowed_actions = ['changeTheme'];

    protected function init()
    {
        parent::init();
        if ($theme = $this->getRequest()->getSession()->get('theme')) {
            SSViewer::config()->update('theme_enabled', true);
            SSViewer::set_themes([$theme]);
        }            

    }

    public function changeTheme()
    {
        $theme = $this->request->param('ID');
        $existingThemes = Config::inst()->get('SilverStripe\View\SSViewer', 'themes');
        if (in_array($theme, $existingThemes)) {
            SSViewer::config()->update('theme_enabled', true);
            SSViewer::set_themes([$theme]);
            $this->getRequest()->getSession()->set('theme', $theme);
        }

        return $this->redirectBack();
    }        
}

Upvotes: 0

bummzack
bummzack

Reputation: 5875

Yes, you can do that. I suggest you implement an action on your controller that will update the theme. You can then store the currently active theme in the session and use it whenever a page is being visited.

Here's how I'd implement that (in your Page_Controller):

class Page_Controller extends ContentController 
{
    private static $allowed_actions = ['changeTheme'];

    public function init(){
        parent::init();

        if ($theme = Session::get('theme')) {
            Config::inst()->update('SSViewer', 'theme', $theme);
        }
    }

    public function changeTheme()
    {
        $theme = $this->request->param('ID');
        $existingThemes = SiteConfig::current_site_config()->getAvailableThemes();

        if (in_array($theme, $existingThemes)) {
            // Set the theme in the config
            Config::inst()->update('SSViewer', 'theme', $theme);
            // Persist the theme to the session
            Session::set('theme', $theme);
        }

        // redirect back to where we came from
        return $this->redirectBack();
    }
}

Now you have a changeTheme action in your Page_Controller, that means you can use it on every page. Then you can simply trigger a theme change with a link, eg:

<%-- replace otherTheme with the folder-name of your theme --%>
<a href="$Link('changeTheme')/otherTheme">Change to other theme</a>

In the Page.ss template of your base-theme, you can add a link to the theme for cecutients. And in the theme for cecutients, you add a link to the base-theme.

Upvotes: 5

Related Questions