Search code examples
phpsearchyiicgridview

Multi column search on Yii CGridView


I have admin page contain CGridView and connected with user database, I need to make search on CGridView work on multi column not just one.. like this:

I need to find user information by phone number OR user name OR email address, is that possible ? and my code is under the image:

enter image description here

Code

User model: I used OR, but it's not work.. I still search by name only !

public function search()
{
    // @todo Please modify the following code to remove attributes that should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id);
    $criteria->compare('full_name',$this->full_name,'OR');
    $criteria->compare('full_name',$this->landline,'OR');
    $criteria->compare('full_name',$this->mobile_number,'OR');
    $criteria->compare('email_address',$this->email_address,true);
    $criteria->compare('city',$this->city,true);


    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'sort'=>array(
            'defaultOrder'=>'id DESC',
        )
    ));
}

Solution

  • You made little mistakes comparing

    $criteria->compare('full_name', $this->full_name, true, 'OR');
    $criteria->compare('landline', $this->full_name, true, 'OR');
    $criteria->compare('mobile_number', $this->full_name, true, 'OR');
    

    First parameter is field in a database and second is what you filled in a form. You also skipped third parameter which is to allow partial matching. And the forth parameter needs to be 'OR'

    Keep in mind that this is work around, and it can give some headaches later on if you are not careful, because you are storing landline and mobile_phone into $model->full_name.

    I would suggest you add another property to User mode, something like user_info and than use that property to store input from request and compare it with database.

    Example from above will still work, if you wish to improve your code with additional parameter and you can't find your way with it, I'll explain it better, just shout.