0

I have a standard giiant generated view where the main model $model is present. First part of the View is a Detailview widget:

<?=
DetailView::widget([
    'model' => $model,

So far clear. Then comes relations tabs (or blocks):

<?php $this->beginBlock('relatedmodels');
echo GridView::widget(['dataProvider' => new \yii\data\ActiveDataProvider(['query' => $model->getRelatedmodels()]),
...
'columns' => [
    [
        'attribute' => 'calculated',
        'value' => function ($relatedmodel) {return $relatedmodel->getCalculated($model->id);},
    ],

This gives of course an error

Undefined variable: model

Controller is also standard giiant generated:

public function actionView($id) {
    \Yii::$app->session['__crudReturnUrl'] = Url::previous();
    Url::remember();
    Tabs::rememberActiveState();

    return $this->render('view', [
        'model' => $this->findModel($id),
    ]);
}

How can I pass the main model id to the function getCalculated() ? Or how to initialise $model into the anonymous function (is it possible at all) ? Can you please point me to the right direction ?

user2511599
  • 796
  • 1
  • 13
  • 38

1 Answers1

1

You need to use Anonymous function - use() and what is a closure and why does it use the “use” identifier?

$this->beginBlock('relatedmodels');
<?= GridView::widget(['dataProvider' => new \yii\data\ActiveDataProvider(['query' => $model->getRelatedmodels()]),
...
'columns' => [
    [
        'attribute' => 'calculated',
        'value' => function ($relatedmodel) use ($model) {return $relatedmodel->getCalculated($model->id);},
    ],
Insane Skull
  • 9,220
  • 9
  • 44
  • 63