Question

I am working on an autocomplete widget. So far this is my code.

My view:

    <?php
    $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 ) {
            console.log(ui);
            $('#user-company').val(ui.item.id);
     }")],
     ]);
     ?>

    <?= Html::activeHiddenInput($model, 'company')?>

When selecting an option the autocomplete options are updating in my text field but not updating the hidden field.

How can I get the hidden field to update when an option is selected?

Was it helpful?

Solution

You can use these properties:

  • labels - shown in dropdown,
  • value - jumps to input field after selection,
  • id - additional paramter for hiden field usage.

For example:

<input type="hidden" id="user_company" name="user_company" value="qwe">
<?php

  use yii\web\JsExpression;

  echo AutoComplete::widget([
    'name' => 'company',
    'id' => 'ddd',
    'clientOptions' => [
      'source' => [
          ['label'=>'color1', 'value'=>'key1', 'id'=>'c_id1'],
          ['label'=>'color2', 'value'=>'key2', 'id'=>'c_id2']
      ],
      'autoFill'=>true,
      'minLength'=>'0',
      'select' => new JsExpression("function( event, ui ) {
        console.log(ui);
        $('#user_company').val(ui.item.id);
      }")


    ],

  ]);?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top