Dynamic Data Columns For Gridview


I’m rewriting Yii v1 application to v2 and I want to create dynamic list of columns for Gridview.

I don’t know exactly columns before I get data, but I need to format column values. In Yii v1 it was really easy:

foreach ($years as $year)


    $this->columns[]  = array(


            'value'=>'number_format($data[\'m'.$year.'\'], 0, ",", ".")',



But in v2 I don’t know how to pass $year value inside formatting function

foreach ($years as $year) {

    $this->columns[] = [

        //if I leave just attribute, everything works, but without formatting

        'attribute' => $year,

        // we want to use intl formatting with new versions, of course <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />

        'value' =>  function ($data) {

            $fmt = new \NumberFormatter('lt_LT', \NumberFormatter::DECIMAL);

            return $fmt->format($data[???REPLACE_WITH_YEAR_VALUE???]);




Data for Gridview is from SqlDataProvider.

I really missing documentation and examples for one of most powerful component that I used in Yii v1 - CGridView. Datacolumns, rows selection, JS (afterUpdate, selectionChanged) is completely different from v1 and docs how to upgrade is very welcomed.


First, you need to use the "use" identifier for closures to capture local variables. See here.

Second, you can view docs here. Note that Yii 2 is still in beta, so the docs are not complete.

Thank You, amnah

Solved. As I thought this is not the question of Yii, but of my weak php knowledge :(

Yes, I’ve explored documentation, found something on github, something in wiki, something in guide and at last asked here in forum.

I’m not hurry Yii guys, they know better what to do first, but after all I’m expecting to find described the full power of Gridview in this guide (including JS part).

Have a good day