Reputation: 2972
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
Upvotes: 5
Views: 3343
Reputation: 1600
As @Fabrizio said. Insert use
after function signature in value
callable function:
'value' => function ($model) use($totaleDays) {
array_push($totalDays,$model->class->date);
return $model->class->date;
},
For multiple value to pass in to value function you can use as below.
'value' => function ($model) use($var1, $var2....., $varN) {
array_push($totalDays,$model->class->date);
return $model->class->date;
},
Like this use($var1, $var2....., $varN)
Upvotes: 3
Reputation: 3893
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>',
],
Upvotes: 5
Reputation: 33538
While you can definetely pass this variable through use
section of closure, it's wrong in your code. MVC principle is violated, because view it's only for display, and you exposing logic such as array_push
.
I'd recommend to refactor it and place data calculation in model, so you can simply call return $model->yourMethod();
and it will return desired data.
Upvotes: 2
Reputation: 3008
Insert use
after function signature in value
callable function:
[
'attribute' => 'class_id',
'format' => 'raw',
'label' => "Class Date",
'value' => function ($model) use($totaleDays) {
array_push($totalDays,$model->class->date);
return $model->class->date;
},
'footer'=> '<span>Total Days</span>',
],
Upvotes: 5