Categories
symfony

How to handle page representation dynamically

Hi all,

Lets say you want to allow each user’s group to see different page style. You may need to change page layout and css file for this dynamically. Lets imagine we have very similar functionality for a few user groups but we want their dashboard pages look different. Here is the code sample which setup for buyer group separate layout and stylesheet and default layout / stylesheet for default user:

public function preExecute() {
if ($this->getContext()->getUser()->hasCredential(‘buyer’)) {
$this->setLayout(‘layout_buyer’);
$this->getResponse()->addStylesheet(‘style_buyer.css’);
} else {
$this->setLayout(‘layout’);
$this->getResponse()->addStylesheet(‘style.css’);
}
}

The other approach – we can modify view.yml file for each separate action (so for buyers actions we can have separate layout / stylesheet), e.g.

indexSuccess:
layout: layout_buyer
stylesheets: [ -style, style_buyer ]

Interesting thing is that we can use “-style” syntax which means that we stop using “style.css” for this specific action. Please note that we can use it only from view.yml, if you’d like to remove stylesheet from php code – there is no way to do that, i.e. we have

$this->getResponse()->addStylesheet(‘style_buyer.css’)

but we dont have

$this->getResponse()->removeStylesheet(‘style_buyer.css’);

Actually removeStylesheet is added to symfony tickets but I dont think it was implemented until now.