Yii auto-complete example

I didn’t see any concise examples of Yii autocomplete, particularly showing data fetched via a server request, so here is one:

widget function in view:

$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
	'name'=>'person',
	'value'=>$model->person,
//	'source'=>$people, // <- use this for pre-set array of values
	'source'=>'/site/getNames',// <- path to controller which returns dynamic data
	// additional javascript options for the autocomplete plugin
	'options'=>array(
		'minLength'=>'1', // min chars to start search
		'select'=>'js:function(event, ui) { console.log(ui.item.id +":"+ui.item.value); }'
	),
	'htmlOptions'=>array(
		'id'=>'person',
		'rel'=>'val',
	),
));

controller function to filter and return data:

	function actionGetNames() {
	  if (!empty($_GET['term'])) {
		$sql = 'SELECT people_id as id, CONCAT(first_name," ",last_name) as value, first_name as label FROM people WHERE first_name LIKE :qterm ';
		$sql .= ' ORDER BY first_name ASC';
		$command = Yii::app()->db->createCommand($sql);
		$qterm = $_GET['term'].'%';
		$command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
		$result = $command->queryAll();
		echo CJSON::encode($result); exit;
	  } else {
		return false;
	  }
	}

sample data output when user types an “r”, looks like:

[{"id": 1,"value": "Rachel Hammond","label": "Rachel"}, {"id": 18,"value": "Ross King","label": "Ross"}]

This is obviously a simple example but one that can easily be extended. In the example above the optional ‘select’ param is the js function once the user selects a value.

More info see CJuiAutoComplete and jqueryui.com/demos/autocomplete

4 Responses to “ “Yii auto-complete example”

  1. vishnu says:

    thanks for this code

  2. Scott says:

    Thanks for the post. It helped me with this. There is one thing I would mention though. Make sure the rules method is updated to access the data. I was getting a 403 error.

  3. Jason says:

    How would you get the Id value from a POST using PHP? I know you’ll get the name using $_POST['person']. How would you get the id?

Leave a Reply