an attribute is not saved to $model [kartik, select2 widget]

152 Views Asked by At
$url = \yii\helpers\Url::to(['/agitator/grs-data/personalnos']);
<?php
        $grs = empty($model->personal_no) ? '' : GrsData::findOne($model->personal_no)->personal_no;

        echo $form->field($model, 'personal_no')->widget(Select2::classname(), [
            'initValueText' => $grs, // set the initial display text
            'options' => ['placeholder' => 'Search for a voter ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'minimumInputLength' => 3,
                '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(grs_data) { return grs_data.text; }'),
                'templateSelection' => new JsExpression('function (grs_data) { return grs_data.text; }'),
            ],
        ]);
        ?>

This is kartik select2 widget. I use this to search personal data from database, and it shows the results as a list from where it is possible to select. When I select and submit, the attribute 'personal_no' is not saved to $model, it is empty. Here is the controller of the view:

public function actionPersonalnos($q = null, $id = null) {
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = ['results' => ['id' => '', 'text' => '']];
    if (!is_null($q)) {
        $query = new Query;
        $query->select('id, personal_no AS text')
            ->from('grs_data')
            ->where(['like', 'personal_no', $q])
            ->limit(20);
        $command = $query->createCommand();
        $data = $command->queryAll();
        $out['results'] = array_values($data);
    }
    elseif ($id > 0) {
        $out['results'] = ['id' => $id, 'text' => GrsData::find($id)->personal_no];
    }
    return $out;
}

Everything is working fine, just the attribute is not saved to model, this is the problem. Thanks.

0

There are 0 best solutions below