简体   繁体   中英

Yii Framework: Different view (on actionIndex) depending on user's role

I'm a beginner in Yii Framework, and I have a problem I can't fix. I have this in my class controller :

public function actionIndex()
{
  $dataProvider=new CActiveDataProvider('Absence');
  $this->render('index',array(
    'dataProvider'=>$dataProvider,
  ));
}

That gives me a list of all 'absence'.

In my case, 'erty' is logged in and sees a list of every absence. But, with his role, stored in my user's table, I want him to see only a list of absences with his 'Collaborateur alias'. Can someone helps me with it ?

Just create

$criteria=new CDbCriteria;
$criteria->compare('role', $user->role /* replace this with required role*/, true);

And attach it into DataProvider

 $dataProvider  = new CActiveDataProvider('Absence', array( 'criteria'=>$criteria));

Better still, and as it's a business rule, it should go in the Absence data model.

So you can add a scope in your Absence data model:

'mine'=>array(
    'order'=>'a_sort_column DESC',
    'condition'=>'role=:role',
    'params'=>array(
        'owner'=>Yii::app()->user->getState('roles'),
               ),
        ),

and then in your code use

     $dataProvider=new CActiveDataProvider(Absence::model()->mine())

If its relevant you can always use a default scope if this filter is always applied.

If this filter is always applied except in an admin context, think about using another class that extends the Absence model and applies the default scope like

  class myAbsence extends Absence
  {
       public function defaultScope()  {

          return array(
    'order'=>'a_sort_column DESC',
    'condition'=>'role=:role',
    'params'=>array(
        'owner'=>Yii::app()->user->getState('roles'),
               ),
        );
   }

and then in your non-Admin controllers you would use

     $dataProvider=new CActiveDataProvider('myAbsence')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM