yii: ajax autocomplete field

by prettyscripts on 2010-11-13 16:38:00

phpyii

note: CAutoComplete is deprecated as of V113 and replaced with CJuiAutoComplete. Please refer to this post.

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:

PHP:

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

PHP:

<?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]); })",
)) ?>
<?php echo $form->hiddenField($model'data_id'); ?>

note

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

Tags: ajax, autocomplete, php, save, yii

No feedback yet

Leave a comment


Your email address will not be revealed on this site.
PoorExcellent
note: all comments are moderated. do not spam and do not advertise. only comments relevant to the post will be published.
(Line breaks become <br />)
(For my next comment on this site)
(Allow users to contact me through a message form -- Your email will not be revealed!)