简体   繁体   English

Yii框架:根据用户角色的不同视图(在actionIndex上)

[英]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. 我是Yii Framework的初学者,但遇到无法解决的问题。 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. 在我的情况下,“ erty”已登录并看到所有缺席的列表。 But, with his role, stored in my user's table, I want him to see only a list of absences with his 'Collaborateur alias'. 但是,根据他的角色,该角色存储在我的用户表中,我希望他仅看到带有'Collaborateur别名'的缺勤列表。 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中

 $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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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