January 09 2014

example of Yii autocomplete

Tagged Under : ,

Yii
Because I didn’t found any example of Yii autocomplete function. particularly showing how to fetched data via a server request.

For the widget function in view:
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
  'name' => 'username',
  'value' => $model->username,
  'sourceUrl' => array('user/getusername'),//path of the controller
  'options' => array(
    'minLength' => '1', // min chars to start search
    'select' => '' // when the value selected
  ),
));

Now, we start create the getusername action in the UserController file.
if (isset($_GET['term'])) {
  $sql = "SELECT id AS value, username AS label FROM users WHERE username LIKE '%".$_GET['term']."%' ORDER BY username ASC";
  $result = Yii::app()->db->createCommand($sql)->queryAll();
  echo CJSON::encode($result);
  Yii::app()->end();
} else {
  return false;
}

In here need to remind is the statement. we need return the value and label to frontend display.
SELECT id AS value, username AS label
The value is use to display the in the input box, and label is use to listing out all the results.

Make a Comment

You must be logged in to post a comment.