There is a table and a related table in which the headers and values ​​of arbitrary fields are stored.

One element of the main table can have many additional fields. Link id ( tours.id->tourfields.tour_id ). How to display them in a GridView ? The name and value of the field in the base table. GridView displays only a certain number of columns?

With a known number and names, you can manually prescribe them, and if the number and headers are unknown in advance.

 GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'name', 'qadult', 'qchildren', 'qbaby', //Тут добавить еще произвольное количество столбцов с //заголовком и значением из таблицы tourfields. ['class' => 'yii\grid\ActionColumn'], ], ]); 
  • Do you need to display absolutely all table fields? - Alexey Shimansky
  • Not all are just name, value from the related tourfields table. name as column heading and value as value. There is a table in which tours and a table with randomly added fields for the tour. - Andrey Goncharenko
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

If the connection in the model is called tourfields

 GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], ... 'tourfields.name', 'tourfields.value', ['class' => 'yii\grid\ActionColumn'], ], ]); 

Or use your columns:

 GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], ... [ 'header' => 'Tourfields Name', 'value' => function($model) { return $model->tourfields->name; } ], [ 'header' => 'Tourfields Value', 'value' => function($model) { return $model->tourfields->value; } ], ['class' => 'yii\grid\ActionColumn'], ], ]); 

The documentation also has examples.

  • I'll try. But it seems not that. Name should be in the column header, not where the value is. - Andrey Goncharenko
  • is tourfields.name the name of the column? - Bookin
  • Yes. Must be in the header of the GridView table. - Andrey Goncharenko
  • I will describe just thoughts, I cannot test at the moment, take out the columns in a separate array, select all possible columns (as I understand it is possible), go through them and add to the array of columns, in the header field - tourfields.name , you can add to value an anonymous function or model method that, by whatever identifier, would get the value for a given column - Bookin
  • the same problem, tell me if it was possible to display the data as you wanted, please share it - Monitorkin