Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable in Gridview function yii2

I am trying to access a variable on view file into Gridview but it is throwing error that it should be array but null given i am declaring $totalDays on top of my view file and i am using it in Gridview like below

[
            'attribute' =>  'class_id',
            'format' => 'raw',
            'label' => "Class Date",
            'value' => function ($model) {
                array_push($totalDays,$model->class->date);
                return $model->class->date;
            },
            'footer'=> '<span>Total Days</span>',
],

But it throws following error

array_push() expects parameter 1 to be array, null given

like image 394
Mike Ross Avatar asked Dec 23 '15 22:12

Mike Ross


1 Answers

To explain, $totalDays is not available in the widget because the whole function only gets run when the widget is rendered, $totalDays is no longer declared. As @arogachev hinted above, you will need to make $totalDays in your model, then you can access it. Try this in your model;

public function getTotalDays(){
//Your logic here to generate totalDays
return $totalDays;
}

Then you can use it in your view like this;

[
    'attribute' =>  'class_id',
    'format' => 'raw',
    'label' => "Class Date",
    'value' => function ($model) {
        array_push($model->totalDays, totalDays,$model->class->date);
        return $model->class->date;
    },
    'footer'=> '<span>Total Days</span>',
],
like image 91
Joe Miller Avatar answered Sep 25 '22 00:09

Joe Miller