kartik\Select2 in GridView Filter show id instead of name

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.


$formatJs = <<< 'JS'

 var id_user = function (id_user) {

 return id_user.id ? id_user.id : id_user.text;  



 $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'),]




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;


After some debugging, I added a console log in my JS function the id and name are both with the user ID after the page reloads. Applied the same function for the

'templateResult' => new JsExpression('id_user'),

and does what is supposed.

Do you have any other suggestion?

Why don’t you use Kartik GridView [ http://demos.krajee.com/grid ]? It has native Select2 integration and works like a charm…