如何在yii gridview中显示所选记录

时间:2018-04-19 16:23:51

标签: php yii2 yii2-advanced-app

美好的一天,优秀的程序员,请我使用yii gridview显示学生的记录,但我想限制显示给特定学生的记录。请问我该怎么做...这是我的索引

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
         // 'id',
        'student.first_name',
        'student.last_name',
        'studentFaculty.faculty_name',
        'studentDept.department_name',
        'level',
        'stateOfOrigin.state_name',
        'image',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?> 

这是我的控制器

public function actionIndex()
{
    $searchModel = new StudentsSearch(); 
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams)->ArrayHelper::map([ Students::find()->where('student_id'=> yii::$app->user->identity->id)->all()]);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

3 个答案:

答案 0 :(得分:0)

将以下代码替换为Controller的索引操作

public function actionIndex(){

$searchModel = new StudentsSearch(); 
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->andWhere(['student_id'=>yii::$app->user->identity->id]); 


return $this->render('index', [
    'searchModel' => $searchModel,
    'dataProvider' => $dataProvider,
]);

}

答案 1 :(得分:0)

好像你正在寻找这样的东西:

学生搜索模型

public function search($params, $filterStudentId)
{
    $query = Students::find();
    $query->andWhere(['student_id' => $filterStudentId]);
    // some code
    return $dataProvider;
}

控制器

public function actionIndex()
{
    $searchModel = new StudentsSearch();
    $params = Yii::$app->request->queryParams;
    $filterStudentId = Yii::$app->user->identity->id;
    $dataProvider = $searchModel->search($params, $filterStudentId);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

答案 2 :(得分:0)

最简单的方法是在不向搜索功能添加任何额外参数的情况下执行此操作,因为管理员也可以将search()函数用于后端,如果在此处添加额外的参数,则需要根据需要修改它们调用它的位置,因此将controller/action更改为以下内容,并在调用student_id模型之前将queryParams分配给StudentsSearch

public function actionIndex()
{
    $searchModel = new StudentsSearch(); 
    $queryParams=Yii::$app->request->queryParams;
    $queryParams['StudentsSearch']['student_id']=Yii::$app->user->id;
    $dataProvider = $searchModel->search($queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

在返回StudentsSearch之前,请确保在student_id函数中搜索您的search()模型字段$dataProvider

$query->andFilterWhere ( ['student_id' => $this->student_id ]);