Friday, 25 January 2013

Yii Autocomplete return multiple values and fill multiple fields

View:

<div class="row">
        <?php echo $form->labelEx($model, 'attribute'); ?>
        <?php
        $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
            'model' => $model,
            'attribute' => 'emp',
            'sourceUrl' => Yii::app()->createUrl('/controller/action'),
            'options' => array(
                'minLength' => '1',
                'select' => 'js:function(event, ui) {
                    $("#field1").val(ui.item.label);
                    $("#field2").val(ui.item.value);
                    return false;
                }'
            ),
            'htmlOptions' => array('size' => 60),
        ));
        ?>
        <?php echo $form->error($model, 'attribute'); ?>
    </div>

Controller:

    public function actionAutocomplete($term) {
        //the $term parameter is what the user typed in on the control
        //send back an array of data:
        $criteria = new CDbCriteria;
        $criteria->compare('field2', $term, true);
        $model = Model::model()->findAll($criteria);

        foreach ($model as $value) {
            $array[] = array('value' => trim($value->field1), 'label' => trim($value->field2));
        }

        echo CJSON::encode($array);
        Yii::app()->end();
    }

No comments:

Post a Comment