Yii: AJAX Autocomplete Field

Note: CAutoComplete is deprecated as of V113 and replaced with CJuiAutoComplete. Please refer to this post if you’re using V113+.

Yii framework comes with CAutoComplete widget for this purpose. However by default, the displayed value is saved to the database.

Thankfully there’s tutorial to show how to display one value but save the id to the database. Codes documented post is based on the tutorial, with some modification to suit my own needs.

Autocomplete action

In controller file, add a new action:

function actionAutocomplete() {
    if (Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {
        $data = lookup_function($_GET['q']);
        $results = array(); 
        foreach ($data as $id => $value) {
            $results[] = $id . '|' . $value;
        }
        echo implode("\n", $results);
    }
}

Notes:

  • $_GET[‘q’] is the default input passed by autocomplete widget.
  • line 3: your own function with the input passed from the widget to lookup data.
  • line 6: “|” is delimiter for jQuery to parse into parts.
  • line 8: “\n” must be enclosed in double quotes. this is separator for eatch items on the list.
  • also line 8: use echo. return will not work!

The form

In form view file:

<?php $this->widget('CAutoComplete', array(
        'name' => 'data_name',
        'value' => isset($model->data_id) ? $model->Data->name : '',
        'url' => $this->createUrl('/path/to/controller/autocomplete'),
        'htmlOptions' => array('size' => '30'),
        'methodChain' => ".result(function(event, item) {\$(\"#<controller_name>_data_id\").val(item[1]); })",
));
echo $form->hiddenField($model, 'data_id');
?>;

Notes:

  • line 3: assuming there’s relation between the current table and Data model.
  • line 6: methodChain appends the code to Autocomplete javascript. result method is fired when an item is selected and assign the value after ‘|’ to hidden field.
  • line 8: hidden field to store the id that is to be saved to database.
  • hidden field: actual name of the field is [name of current controller]_data_id, hence that needs to be specified in line 6.

2 thoughts on “Yii: AJAX Autocomplete Field

  1. Mnagesh Reply

    not working for me.request cant get on controller site.

Leave a Reply

Your email address will not be published. Required fields are marked *