I am having difficulty getting the filtering to work in CGridView for relational fields from another model.
URL Reference: Yii 1.1: Searching and sorting by related model in CGridView
I follow the codes and it seems to be returning me the inputs from the other model. Everything looks fine but unfortunately, the filter is not working.
On Search, it will display a quick load icon but failed to filter accordingly. Upon checking further, I noticed the input is wrong. I am using Google Inspect Element and noticed the following:
<input name="User[full_name]" type="text">
I am using User model, relational to Biodata. Shouldn't it be Biodata[full_name]? If this is, where should I be looking at the codes?
Thank you. :D
Filtering and sorting in CGridView
widget can be done in few steps:
1. Add virtual field to your User
model. It will be used to create column in CGridView; it also needed for proper filtering and sorting:
class User extends CActiveRecord
{
public $bioFullName;
//...
}
2. Modify search()
function in your User
model. You need to add array parameter to this function and add to $criteria
object in this method connection with related model. To add sorting of related attribute, you also need to modify returned CActiveDataProvider
. See what happens below:
public function search($params = array()) // <-- new parameter that handling params for searching
{
$criteria = new CDbCriteria($param);
$criteria->with = array('biodata'); //add relation with Biodata to $criteria object
// ... existing $criteria conditions
$criteria->addSearchCondition('biodata.full_name', $this->bioFullName, true, 'AND'); // add comparison of biodata.full_name
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
// ...
'sort'=>array(
'attributes'=>array(
'bioFullName'=>array( // <-- sorting of related field
'asc'=>'biodata.full_name ASC',
'desc'=>'biodata.full_name DESC',
),
'*',
),
),
));
}
3. Adjust CGridView
widget in your view to show related column. In columns
array of widget configuration add column named like virtual field from model (bioFullName
):
<?php
$this->widget('zii.widgets.grid.CGridView', array(
// ... other widget configuration options
'columns'=>array(
// ... other columns
'bioFullName'=>array(
'name'=>'bioFullName', // <-- name of virtual model field
'value'=>'$data->biodata->full_name', // <-- getting field value from relation
'header'=>'Full name', // <-- CGridView column header
),
// ... other columns
),
));
?>