Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocomplete in yii2

In Yii2 I want one of my input field to be autocomplete when user starts to type.Below is my code which uses Jui Autocomplete.

 <?php
    $items= ArrayHelper::map(Company::find()->all(), 'c_id', 'name');
    echo AutoComplete::widget([
    'model' => $model,
    'attribute' => 'company',
    'clientOptions' => [
    'source' => $items,
     ],
    ]);?>

This is not working.When i printed my array, i got like

 Array ( [1] => abc [2] => xyz [4] => pqr )

I got it working when i manually set like

 $items=['abc','xyz','pqr'];

The reason may be my c_id's are not ordered?But i want to get the c_id value to be submitted!Any idea how to fix this?

like image 738
Dency G B Avatar asked Apr 22 '14 09:04

Dency G B


1 Answers

This can be solved with the help of a hidden field input.Hope this will help somebody!

    <?php
    use yii\web\JsExpression;

    $data = Company::find()
    ->select(['name as value', 'name as  label','c_id as id'])
    ->asArray()
    ->all();

    echo AutoComplete::widget([
    'name' => 'Company',
    'id' => 'ddd',
    'clientOptions' => [
        'source' => $data,
        'autoFill'=>true,
        'minLength'=>'4',
        'select' => new JsExpression("function( event, ui ) {
                $('#user-company').val(ui.item.id);
            }")
        ],
     ]);
     ?>

    <?= Html::activeHiddenInput($model, 'company')?>
like image 82
Dency G B Avatar answered Sep 28 '22 00:09

Dency G B