Search Functionality On An Index Page

  1. Let’s say your controller looks like this:

public function actionIndex()

{

$dataProvider=new CActiveDataProvider(‘Model’);

$this->render(‘index’,array(

‘dataProvider’=>$dataProvider,

));

}

  1. Change it to this:

public function actionIndex()

{

$criteria = new CDbCriteria();





if(isset($_GET['q']))


{


  $q = $_GET['q'];


  $criteria->compare('attribute1', $q, true, 'OR');


  $criteria->compare('attribute2', $q, true, 'OR');


}





$dataProvider=new CActiveDataProvider





        ("Model", array('criteria'=>$criteria));





$this->render('index',array(


  'dataProvider'=>$dataProvider,


));

}

The above will read in the “q” (for query) parameter, and use the compare function to create the sql to search a few attributes for that value. Note the use of the ‘OR’ operator.

  1. In your index view, add this:

<form method="get">

<input type="search" placeholder="search" name="q"

value="<?=isset($_GET[‘q’]) ? CHtml::encode($_GET[‘q’]) : ‘’ ;

?>" />

<input type="submit" value="search" />

</form>

The above creates a form that will submit to itself using the querystring. It displays a search input box, which is a text input box with a "cancel" command. It works in most browsers and defaults to a text field in the rest. When the user hits the search button, the form is submitted and the data is filtered by the search value.

screenshot :

Hey Karmraj,

Excellent article.

I was searching for the custom search and this post served my requirement.

Karmraj, just what I needed , it’s a great idea, thank you so much.