How to pass an array as a parameter to a gridview column Yii2

I am trying to pass $arr_judete_v2 as a parameter to a callback function in gridview and does not work;

$model['county_id'] returns a number

$arr_judete_v2[1]['nume'] returns the name

my problem:

 [ 'attribute' => 'county_id', 'label' => Yii::t('diverse', 'Judet'), 'content' => function($model, $arr_judete_v2) { return $arr_judete_v2[$model['county_id']]['nume']; }, ], 

whole gridview

 <?php echo GridView::widget([ 'layout' => "{items}", 'dataProvider' => $dataProvider, 'columns' => [ 'id', [ 'attribute' => 'nume', 'label' => Yii::t('companie', 'nume'), ], 'cui', 'email', [ 'attribute' => 'county_id', 'label' => Yii::t('diverse', 'Judet'), 'content' => function($model, $arr_judete_v2) { return $arr_judete_v2[$model['county_id']]['nume']; }, ], [ 'class' => 'yii\grid\ActionColumn', 'template' => '{update} {delete}', 'buttons' => [ 'update' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['update', 'id' => $model['id']], [ 'title' => Yii::t('yii', 'Update'), 'data-pjax' => '0', ]); } ] ], ], ]); 
+5
source share
2 answers

From source code for \ Yii \ grid \ Column

@var callable This is the callable that will be used to create the contents of each cell. The signature of the function should be as follows: function ($model, $key, $index, $column)

As Mihai correctly pointed out , you can use use() to include variables in the function scope as follows:

 "content" => function($model, $key, $index, $column) use ($arr_judete_v2) { return $arr_judete_v2[$model['county_id']]['nume']; } 

Note that the variables are copied to the function, and therefore any changes will not affect the variable outside the function. The best explanation for this is given in this answer .

+10
source

Use use (), see how the function is defined for the column value.

  $invoice_status_data = array('' => 'Select a status') + ArrayHelper::map(InvoiceStatus::find()->asArray()->all(), 'id', 'name'); ........................ 'columns' => [ ........................ [ 'attribute'=>'Contact.name', 'format'=>'raw', 'value'=>function ($model, $key, $index, $widget) use ($invoice_status_data) { ............................. $content .= Html::dropDownList('dropdown'. $model->id, '', $invoice_status_data, [ 'class' => 'form-control', 'onchange' => 'javascript: myInvoice.change($(this));', 'data-href' => Url::toRoute(['invoice/change-status', "Invoice_id"=>$model->id])]); return $content; }, ], 
+2
source

Source: https://habr.com/ru/post/1200093/


All Articles