Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: Jui Auto Complete Widget how to?

I am trying to use yii2 Jui autocomplete widget.

I have this code which is showing the auto-complete date correctly, but I am not able to save the data.

$data=ArrayHelper::map(State::find()->all(), 'id', 'state_name' );
$data=array_merge($data);

And then

echo 'State' .'<br>';
  echo AutoComplete::widget([
    'model'=>$model,
    'attribute' => 'state_id',     
    'clientOptions' => [
        'source' => $data,        
    ],
]);

Any solution will be greatly appreciated. Thanks.

like image 438
Pawan Avatar asked Feb 07 '15 18:02

Pawan


1 Answers

Ok I found the solution, it goes like this:

use yii\jui\AutoComplete;
use yii\web\JsExpression;

Then:

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

Then

echo 'State' .'<br>';
  echo AutoComplete::widget([
    'name' => 'State',    
    'id' => 'ddd',
    'clientOptions' => [
        'source' => $data, 
        'autoFill'=>true,
         'select' => new JsExpression("function( event, ui ) {
        $('#city-state_name').val(ui.item.id);//#City-state_name is the id of hiddenInput.
     }")],
     ]);

and Finally:

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

That is all. Hope some one will find it useful. Thanks.

like image 89
Pawan Avatar answered Oct 01 '22 04:10

Pawan