yii: autocomplete field with CJuiAutoComplete

by prettyscripts on 2012-01-20 14:17

phpyii

i have previously written a post on the same topic with CAutoComplete. since CAutoComplete is deprecated (since V113) and replaced with CJuiAutoComplete, i should keep my notes up-to-dated.

i find that CJuiAutoComplete is easier to implement. the following is based on a this forum post.

view file or the form

PHP

<?php $this->widget('zii.widgets.jui.CJuiAutoComplete'array(
    'model' =&gt$model,
    'attritube' =&gt'name_of_attribute',
    'name' =&gt'name_of_field',
    'value' =&gt'default_display_value',
    'source' =&gtcreateUrl('/path/to/controller/autocomplete'),
    'options' =&gtarray(
        'minLength' =&gt2,
        'select' =&gt"js:function(event, ui) {
            $('#<field_id>').val(ui.item.['<id>']);
            }",
        'change' =&gt"js:function(event, ui) {
            if (!ui.item) {
                $('#<field_id>').val('');
            }
            }",
    ),
)) ?>

notes:

  • line 4: do not use codes line 2-3 this field is for display a value. ensure there's a hidden field on the form to be saved to the database.
  • lines 9 - 15: optional. for situation such as to display value on a field but save the id to database.
  • line 10: eg set hidden field with the actual data value to be saved to database, see next section regarding <id>
  • lines 12 - 15: clear field value if data is empty

autocomplete action

in controller file, add a new action:

PHP

function actionAutocomplete() {
    if (Yii::app()-&gt;request-&gt;isAjaxRequest &amp;&amp; isset($_GET['term'])) {
        $models Model::model()-&gt;getData($_GET['term']);
        $result array();
        foreach ($models as $m)
            $result[] = array(
                'label' =&gt$m-&gt;attribute_displayed_in_drop down_list,
                'value' =&gt$m-&gt;attribute_for_input_field,
                'id' =&gt$m-&gt;attribute_for_hidden_field_or_to_be_saved,
                'field' =&gt$m-&gt;attribute_for_another_field,
            );
 
        echo CJSON::encode($result);
    }

notes:

  • line 7: can be formatted string to be displayed on the drop down list.
  • line 8: value to be displayed in current input field
  • line 9-10: optional. values to be set on another field on the same form. refering to line 8 above. can be accessed as array.