Yii2 GridView Problem

Dear All :

I create a table and below is my code about GridView




<?= GridView::widget([

    'dataProvider' => $dataProvider,

    'filterModel' => $searchModel,

    'columns' => [

        ['class' => 'yii\grid\SerialColumn'],

        [

            'attribute' => 'firstName',

        ],

        [

            'attribute' => 'lastName',

        ],

    ],

]); ?>



It can list the data and filter firstName or lastName in search input.

Here is my problem.

I save these two attributes into two columns in my database.

But!!!!! I want to show two values into one column in frontend.

Just like this :




<?= GridView::widget([

    'dataProvider' => $dataProvider,

    'filterModel' => $searchModel,

    'columns' => [

        ['class' => 'yii\grid\SerialColumn'],

        [

            'attribute' => 'firstName',

            'value' => function () {

                  return $model->firstName.$model->lastName;

            },

        ],

    ],

]); ?>



It’s fine in frontend, the list data will show the right value in grid form.

But the filter input can’t search value about the lastName, only the firstName can be searched.

I know because the query condition i wrote didn’t right.




$query->andFilterWhere(['like', 'firstName', $this->firstName])

    ->andFilterWhere(['like', 'lastName', $this->lastName]);



Is there any solution about merging two attributes into one cloumn and searching the correct value?

Please help. Thx!!!!!

I tried doing this modifying the search model eg,

$query = Customer::find()->select(‘CONCAT(first_name, last_name) AS name’);

$query->andFilterWhere([‘like’, ‘name’, $this->name])

However, this breaks the pagination as the name field is excluded from the count. You could try using a sql provider for the grid instead of an activedataprovider.

http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html

This seems like a common use case, pls post any good solutions you find, I will do likewise.

Scenario 1 in Kartik’s tutorial is probably what you are looking for. It’s a very good tutorial.