Thursday, December 2, 2010

YII » How to setup an AJAX autocomplete field

In your view (_form.php), add this:

<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
 'name'=>'name',
 'sourceUrl'=>'suggestName'
, 'value'=>'some initial value;
 ));
?>
If you are using a model, use the model and attribute parameters for the widget instead of the name and value parameters

In your controller, add a method:

public function actionSuggestName($term)
{
  //the $term parameter is what the user typed in on the control

  //send back an array of data:
  echo CJSON::encode(array('one', 'two', 'three'));

  Yii::app()->end(); 
}

In your controller, in accessRules(), allow authenticated users to use the suggestName action:

array('allow', 
  'actions'=>array('create','update', 'suggestName'),
  'users'=>array('@'),
   ),

3 comments:

  1. Hello,
    thank you for this article.

    Actually i copied the code and i looks nice, but I can't notice the ajax action. There is no activity in Firebug?

    thank you

    ReplyDelete
  2. How can i select multiple values using this field.

    ReplyDelete
  3. Thanks for your effort.

    ReplyDelete