Search code examples
phpsqldatabaseyii2dataprovider

How to modify results generated by Yii2 createCommand() function


I have a SQL query in my controller. The results have two fields: id_person and name_person. Then I use ArrayDataProvider to show the results in a GridView:

return new ArrayDataProvider([
    'allModels' => Yii::$app->getDb()->createCommand($mySql)->queryAll()
]);

But the id of the update button is not id_person. It has an id auto generated.

So I have a data provider with the fields: id, id_person and name_person. I need to replace id by id_person.

I can resolve it in my view file under the action of update button but it could be better to resolve it in my controller.

I checked the API Documentation for Yii 2.0 but It doesn't help me.


Solution

  • You should configure ArrayDataProvider::$key property to specify column with record ID:

    return new ArrayDataProvider([
        'allModels' => Yii::$app->getDb()->createCommand($mySql)->queryAll(),
        'key' => 'id_person',
    ]);