Reputation: 129
In my requirment i want to list the gridview with relational data, i have a two table tbl_work(id,workid,cdr_id(foreign_key of tbl_cd)) and tbl_cd(id,caller,called).
in work model and cd model having hasone relation. then i was created a grid with the tb_work table and show the tbl_cd table records.
search function in work model
$query = AuditorWorkItems::find();
$query->with("cd");
// 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;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'workid' => $this->workid,
'cdr_id' => $this->cdr_id
]);
return $dataProvider;
in my grid
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'cdr_id',
'value' => function ($model) {
return $model->cdr->called;
},
],
[
'attribute' => 'cdr_id',
'value' => function ($model) {
return $model->cdr->caller;
},
],
Its show the called and caller value but filter is not working, do you have any other idea to implement this with all the column in tbl_cd table
Upvotes: 0
Views: 4380
Reputation: 291
Step 1 :
Define a variable in your search model:
public $calledValue;
Step 2 :
In rules apply the required rule.
[['calledValue'], 'safe'],
Step 3 :
If you want to sort data with respect to that column in your search model before loading parameters write this code :
$dataProvider->sort->attributes['calledValue'] =
[
'asc' => ['tbl_cd.called' => SORT_ASC], // TABLE_NAME.COLUMN_NAME
'desc' => ['tbl_cd.called' => SORT_DESC],
];
Step 4 :
Now to filter the data add this code in your grid filtering conditions.
$query->andFilterWhere(['like', 'tbl_cd.called', $this->calledValue]);
Step 5 :
Now in your Index file write this code :
[
'attribute' => 'calledValue', //To display called value
'label' => 'Your Label',
'value' => 'tbl_cd.called'
],
Upvotes: 10