Yii Framework Forum: Search Functionality On An Index Page - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Search Functionality On An Index Page How to implement simple and easy search functionality on an index page

#1 User is offline   karmraj 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 14
  • Joined: 30-January 12
  • Location:Ahmedabad

Posted 03 April 2013 - 02:34 AM

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

public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Model');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}

2. 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.

3. 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 :

Attached File(s)


Karmraj Zala,
Team Leader at Rudrasoftech,
Ahmedabad, Gujarat, India.
4

#2 User is offline   PHP Senior Developer 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 19-April 15
  • Location:http://code2real.blogspot.in/

Posted 23 June 2015 - 11:33 PM

Hey Karmraj,

Excellent article.

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

#3 User is offline   franjalafa 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 17
  • Joined: 17-September 13
  • Location:México

Posted 30 September 2015 - 06:39 PM

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

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users