Autofill in yii2

In Yii2, I want one of the input fields to be autocompleted when the user starts typing. Below my code uses Jui Autocomplete .

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

This does not work. When I printed my array, I got how

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

I worked when I manually set how

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

Perhaps the reason is that my c_id's not ordered, but I want to get the c_id value. Any idea how to fix this?

+7
php autocomplete yii2
source share
2 answers

This can be solved by using a hidden input field. Hope this helps someone!

  <?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')?> 
+12
source share

Autocomplete simply helps to fill in the field with the required value. If you need to send c_id look in dropdownList or Select2 plugin.

Check out this http://demos.krajee.com/widget-details/select2 yii2 widget for ideas. Here is a sample code:

 <?php use kartik\widgets\Select2; use app\models\Modelname; $model = new Modelname; $data = ['qwe1'=>'color1','key2'=>'color3'] ?> <?= Html::beginForm() ?> <?= Select2::widget([ 'model' => $model, 'attribute' => 'color', 'data' => array_merge(["" => ""], $data), 'options' => ['placeholder' => 'Select a state ...'], 'pluginOptions' => [ 'allowClear' => true ], ]); ?> <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?> <?= Html::endForm() ?> 

It also supports data uploaded by ajax: http://demos.krajee.com/widget-details/select2#ajax

+1
source share

All Articles