Posts Tagged with yii model search

Displaying 1-1 of 1 result.
Wiki: Yii 1.1 Cgridview TextField Search and Filter of a relations field without errorswiki
posted by admin on October 11, 2016
1) Add some public attribute to the model.

class Customer extends CActiveRecord
{
public $customername; // for firstname + lastname;
....

2) Declare it safe on search.

public function rules()
{
return array(
....
array('id, firstname, lastname, ...., customername', 'safe', 'on'=>'search'),
);
}

3) Set the label for it.

public function attributeLabels()
{
return array(
'id' => 'ID',
'firstname' => 'First Name',
'lastname' => 'Last Name',
....
'customername' => 'Customer Name',
);
}

4) Add a search condition for it in "search()" method.

public function search()
{
$criteria=new CDbCriteria;

$criteria->compare('id',$this->id);
$criteria->compare('firstname',$this->firstname);
$criteria->compare('lastname',$this->lasttname);
....
if ( $this->customername != "" )
{
$crit2 = new CDbCriteria;
$crit2->compare('firstname', $this->customername , true, 'OR');
$crit2->compare('lastname', $this->customername , true, 'OR');
$criteria->mergeWith($crit2);
}
....

5) Add the sorting rule for it, also in the "search()" method.

....
return new CActiveDataProvider(get_class($this), array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 'lastname, firstname',
'attributes' => array(
'customername' => array(
'asc' => 'lastname, firstname',
'desc' => 'lastname DESC, firstname DESC',
),
'*',
),
),
'pagination' => array(
'pageSize' => 20,
),
));

6) And use the attribute in the grid.

$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'customer-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
....
array(
'name' => 'customername',
'value' => '$data->firstname . " " . $data->lastname',
),
....
Read more