Add Condition In Yii Search


I have a list view populated using cgridview. Outside the grid view i have a seach form where various parameters can be entered. On clicking submit form, i should be able to get the searched result using the values provided.

I have succeeded in filtering the results using single variable. But when multiple values are to be searched i cannot make it to work.

Controller :

$this -> layout = 'main';


$search = $_GET['search_key']; 	

$model->firstName = $search;  

$model->lastName = $search;  

$model->email = $search;


$this -> render('staffmanagement', array('model' => $model));

Model :

public function search()


		// Warning: Please modify the following code to remove attributes that

		// should not be searched.

		$criteria=new CDbCriteria;













		return new CActiveDataProvider($this, array(




View :


echo CHtml::beginForm('', 'get'); 

echo(CHtml::textField('search_key', '',array('class' => 'search_txt', 'placeholder' =>'Search')));

echo CHtml::endForm(); 


When i remove all the addCondition() in model




as well as remove two values from controller

$model->lastName = $lastName;  

$model->email = $email;

the search works perfectly for a single value (firstName).

How can i add other two parameters also and keep the form working ?

I’m guessing your ‘OR’ conditions are causing the problem. These won’t nest in the way you’re expecting them to.

I think you’ll need to create a separate CDbCriteria object to manage your OR conditions and then merge it with the original CDbCriteria using an AND condition.

please to through

I solve this problem by

  1. define an attibute in model within class like public $my_variable

  2. add this to search in rules

3)add field (defined in 1) to search form

In Search (Model)

if ($this->my_variable) {

$criteria->addCondition(‘my_variable=’.$this->name.’ OR…’); // add your condition(>,=,<,like %something%) and go through above link


Please don’t promote SQL injection vulnerabilities in a framework that’s very good at preventing them.

ok, thanks

I’d use a dedicated search model for this. It basically contains all attributes you want to search for and the ususal search() method. This way you keep your active record more clean and can focus on the search task better. See an example here.

In your view file you would render a regular Yii form for this search model. And in your controller action you use this model instead of the active record: You assign the search attributes and fetch the provider through search().