Search Functionality On An Index Page

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

public function actionIndex()


$dataProvider=new CActiveDataProvider(‘Model’);





  1. Change it to this:

public function actionIndex()


$criteria = new CDbCriteria();



  $q = $_GET['q'];

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

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


$dataProvider=new CActiveDataProvider

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





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" />


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.