0
votes

I use select2 ajax loading. I get the code from this link: http://demos.krajee.com/widget-details/select2. When I enter words into field, it display all data/value, but it can't automatic select data/value according to words that I enter into field. So, my select2 always select the first data/value and display all value. What's the problem? These are the codes:

_form.php

$url = Url::to(['/paket/jsonlist']);

    $cityDesc = empty($model->no_induk) ? '' : Penerima::findOne($model->no_induk)->nama;

    echo $form->field($model, 'no_induk')->widget(Select2::classname(), [
        'initValueText' => $cityDesc, // set the initial display text
        'options' => ['placeholder' => 'Search for a city ...'],
        'pluginOptions' => [
            'allowClear' => true,
            'minimumInputLength' => 1,
            'language' => [
                'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
            ],
            'ajax' => [
                'url' => $url,
                'dataType' => 'json',
                'data' => new JsExpression('function(params) { return {q:params.term}; }')
            ],
            'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
            'templateResult' => new JsExpression('function(no_induk) { return no_induk.text; }'),
            'templateSelection' => new JsExpression('function (no_induk) { return no_induk.id; }'),
        ],
    ]);

my controller:

public function actionJsonlist($q = NULL, $id = NULL)
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];

        if(!is_null($q))
        {
            $query = new \yii\db\Query;
            $mainQuery = $query->select('no_induk AS id, nama AS text')
                               ->from('penerima')
                               ->limit(20);
            $command = $mainQuery->createCommand();
            $data = $command->queryAll();
            $out['results'] = array_values($data);
        }
        elseif ($id > NULL)
        {
            $out['results'] = ['id' => $id, 'text' => \frontend\models\Penerima::find($id)->nama];
        }
        return $out;
    }
1

1 Answers

0
votes

Could be you use the attribute name and not the vars

   echo $form->field($model, 'no_induk')->widget(Select2::classname(), [
    'initValueText' =>'cityDesc', // set the initial display text

or

   echo $form->field($model, 'no_induk')->widget(Select2::classname(), [
    'initValueText' =>$model->cityDesc, // set the initial display text