Сообщество IT-специалистов
Ответы на любые вопросы об IT
Профессиональное развитие в IT
Удаленная работа для IT-специалистов
/******* * View ******/ // The controller action that will render the list $url = \yii\helpers\Url::to(['city-list']); // The widget use kartik\widgets\Select2; // or kartik\select2\Select2 use yii\web\JsExpression; use app\models\City; // Get the initial city description $cityDesc = empty($model->city) ? '' : City::findOne($model->city)->description; echo $form->field($model, 'city')->widget(Select2::classname(), [ 'initValueText' => $cityDesc, // set the initial display text 'options' => ['placeholder' => 'Search for a city ...'], '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(city) { return city.text; }'), 'templateSelection' => new JsExpression('function (city) { return city.text; }'), ], ]); /************* * Controller ************/ public function actionCitylist($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, name AS text') ->from('city') ->where(['like', 'name', $q]) ->limit(20); $command = $query->createCommand(); $data = $command->queryAll(); $out['results'] = array_values($data); } elseif ($id > 0) { $out['results'] = ['id' => $id, 'text' => City::find($id)->name]; } return $out; }