Search code examples
yii2dataprovider

Use closures in Yii2 ArrayDataProvider


In an ActiveDataProvider you can use closures as values, like:

$dataprovider = new ArrayDataProvider([
    'allModels' => $array
]);

$gridColumns = [
    'attrib_1',
    [
        'attribute' => 'attrib_2',
        'label' => 'Label_2',
        'value' => function($model) {
            return Html::encode($model->value_2);
        }
    ],
    'attrib_3'
];

echo GridView::widget([
    'dataProvider'=> $dataprovider,
    'columns' => $gridColumns
]);

Is it possible to do the same or something like this, in an ArrayDataProvider?


Solution

  • Yes. Only difference is that $model is not an object but array so:

    'value' => function($model) {
        return Html::encode($model['value_2']);
    }