HOW TO PASS FILTERED MODEL TO GRID VIEW IN YII 2

gridview-accdg-to-filtered-model.png

Do you want to display records which have already been filtered beforehand in gridview? For example, records based on the logged user…

Here’s how:

Duplicate your Search model and change its name. Add a second parameter that will be used. In this case, $student. Add conditions to find() ->where(). In this case, you want to show records with the passed student no.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public function search($params, $student)
{
$query = Application::find()->where(['studentuser_studentNo'=>$student]);
// add conditions that should always apply here
 
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
 
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
return $dataProvider;
}
}


Create a separate form for your gridview. You can use default grid view or gridview extensions. In my case, I used kartik gridview. Anyway, important thing is you passed and used searchmodel and dataprovider.

Add your function in your controller. Define the second parameter to be passed. For example, you can use a model, search for it and assign the attribute to a variable. Call the second search model and pass the two parameters. Just add the second parameter. Render the newly created view while passing searchmodel and dataprovider.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public function actionStudent()
{
$id = Yii::$app->user->id;
 
$students = Student::findOne(['user_id'=>$id]);
$student = $students->studentNo;
 
$searchModel = new ApplicationSearch2();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $student);
 
return $this->render('app/student', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
 
]);
}


Post a Comment

0 Comments