I have a Gridview and in the dropdown I decide to implement a select2 dropdown using ajax, has the page was taking too long to load, after implementing the ajax the performance improved a lot and works fine the ajax search. My issue is when I select a name from the list the page reloads and gets the data from that id that I selected, but in the filter header, it shows the id instead of showing the name. The code below is only for the user, but the column for Organization and Message also have the same issue.
view/index.php
$formatJs = <<< 'JS'
var id_user = function (id_user) {
return id_user.id ? id_user.id : id_user.text;
}
JS;
$this->registerJs($formatJs, \yii\web\View::POS_HEAD);
...
[
'attribute' => 'id_user',
'label' => Yii::t("app", "User"),
'value' => function ($model) {
return Notification::findOne($model->id)->idUser->name;
},
'filterType' => GridView::FILTER_SELECT2,
'filterWidgetOptions' => ['options' => ['placeholder' => ''], 'pluginOptions' => ['allowClear' => true, 'minimumInputLength' => 3,
'ajax' => [
'url' => Url::to(['user-list']),
'dataType' => 'json',
'data' => new JsExpression('function(params){return{q:params.term};}'),
'cache' => true,
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateSelection' => new JsExpression('id_user'),]
],
],
Controller.php
public function actionUserList($q = null, $id = null) {
Yii::$app->response->format = Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select('id, name AS text')->from('tbl_user')->where(['like', 'name', $q])->limit(10);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
} elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => User::find($id)->name];
}
return $out;
}