Scriptbaker
ScriptbakerAI & Software Engineering
Yii

Switch Yii layout based on user role

You can assign different layouts to different users using following filter class 1. Add LayoutFilter.php to your protected/components/ folder [code language=

· 5 min read

You can assign different layouts to different users using following filter class

1. Add LayoutFilter.php to your protected/components/ folder

 class LayoutFilter extends CFilter { protected function preFilter($filterChain) { // logic being applied before the action is executed $roles = Yii::app()->user->getState('roles'); if (!is_array($roles)) $roles = array(); if (in_array(User::ROLE_ADMIN, $roles)) { $filterChain->controller->layout = 'admin/column2'; } else { $filterChain->controller->layout = '//layouts/column2'; } return parent::preFilter($filterChain); } protected function postFilter($filterChain) { // logic being applied after the action is executed return parent::postFilter($filterChain); } } 

2. Update protected/components/Controller.php and add following filters

 public function filters() { return array( 'rights', array('application.components.LayoutFilter'), ); } 

3. Update all controllers and add following filters

 public function filters() { return parent::filters() + array( 'postOnly + delete', // we only allow deletion via POST request ); }