realtebo
realtebo

Reputation: 25691

Yii2: Is it possible to set visibile default value for an Autocomplete Widget?

I initialize a model, and one attribute of it, on my controller

$model = new MyModel;
$model->internal_code = 'BAUBAU';

Then I populate an array of codes suitable for autocomplete

$products = Product::find()
                ->select([
                        Product::tableName().'.id as id',
                        'internal_code as label',
                        'internal_code as value',
                    ])
                ->asArray()
                ->all();

Then I'd like to use an autocomplete to show the default value AND allow user to change it selecting via autocomplete widget.

This the View code

echo $form->field($model, 'internal_code')
    ->widget(AutoComplete::classname(),[
        'clientOptions' => [
                'source'    => $products
            ]
        ])
    ->label('Internal code');

Actually the widget works, user can digit chars and select from the results of autocomplete narrowed search.

Bu the problem is that even if $model->internal_code is set, the widget, at loading, do not shows the value. The user don't see the default value ('BAUBAU') on screen. I'm not able to understand what property and/or client option to fill.

Note: I added jquery-ui tag because this Yii2 widget uses the autocomplete widget of JqueryUI

Upvotes: 3

Views: 1314

Answers (2)

paskuale
paskuale

Reputation: 13

default value you can set in options array, view below:

'options' => [
                    'placeholder'=> 'Select...',
                    'class'=>'form-control',
                    'value' => (!empty($model->attribute) ? $model->attribute : ''),
            ],

Upvotes: 0

GAMITG
GAMITG

Reputation: 3818

You just need to set value property.

Like this.

echo $form->field($model, 'internal_code')
    ->widget(AutoComplete::classname(),[
        'value' => (!empty($model->internal_code) ? $model->internal_code : ''),
        'clientOptions' => [
                'source'    => $products
         ]
 ])->label('Internal code');

Upvotes: 4

Related Questions