Search code examples
phpyii-extensionsyii2

Yii2 Autocomplete : Save the ID instead of value


I have a list of array called as datalist which contains the name of companies with id.when i use it with the typeahead widget,it captures the value of company with the variable coSearch(id of input).but i want to display the list of companies and when selected,it must give the vale of that id in variable .i am really messed with this problem working from three days.Please help me out. Here is the code for my activeform which contains the widget.

<?php 
    $form = ActiveForm::begin([
    'action' => ['search'],
    'method' => 'get',
    ]); 
    $dataList=ArrayHelper::map($companies, 'id', 'name');
    echo Typeahead::widget([
    'model' => $companySearched, 
    'name'=>'coSearch',
    'options' => ['placeholder' => 'Search  company','id'=>'searchCompany1','class' => 'form-      control','value'=>'1'],
    'pluginOptions' => ['highlight'=>true],
    'dataset' => [
        [
            'local' =>  $dataList,
            'limit' => 10,
        ]
    ]
]);


?>

Solution

  • This can be solved with the help of a hidden field.I use autocomplete here

    <?php
    use yii\web\JsExpression;
    use yii\jui\AutoComplete;
    
    $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 ) {
        $('#model-company').val(ui.item.id);
     }")],
     ]);
     ?>
    
     <?= Html::activeHiddenInput($model, 'company')?>
    

    Hope this help!