There is a GridView , but the categories are displayed in the form of numbers. How to display names from another table - categories instead of these figures by Category_id-Title? Yii2 is very difficult.

Gridview

What do I need to write in the code? I tried differently, and here I took it, and here . But everything ended in errors. Thanks for the help! Code

  • I advise you and now continue to upload your code here not in the form of a screenshot, but directly in a text formatted form. SO editor allows it. In case the code is large, no one wants to try to reproduce it by manually typing it in ... - Alexey Shimansky
  • Relational category.title not working? - Andrey Kolomensky
  • @ Onedev.Link registered the link in the hasOne models. But in the form it is not possible to withdraw using categories.Title - Benjamin Button
  • @BenjaminButton categor ies this is not like hasOne :) Check that you can just make echo $model->category->title in the view next to the GridView and in the columns try to stuff category.title . - Andrey Kolomensky

2 answers 2

 [ 'attribute' => 'category_id', 'filter' => Html::activeDropDownList( $searchModel, 'category_id', ArrayHelper::map(Category::find()->all(), 'id', 'name'), ['class' => 'form-control'] ), 'value' => 'category.name', ] 

This method still works, do not pay attention to the filter, I'm talking about 'value' => 'category.name' . I do not know whether this is more beautiful than in the previous version, but I myself am new. It works like this, can someone tell from experienced what is the difference?

  • Sorry, of course, but the sample in the submission smells bad. Yes, and so much code for the sake of output properties - the beauty is pretty dubious. - BrusSENS

It is required to first define the relationships in the model, for example, you have models for the Category and Data tables, then the category model will have this method:

 public function getData() { return $this->hasOne(Data::className(), ['id' => 'data_id']); } 

Much detail here is chewed about Active Record.

Next, we can configure our own column directly in the GridView:

 <?php echo GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ [ 'attribute' => 'id', 'value' => function ($model, $key, $index, $widget) { return $model->data->title; }, 'format' => 'raw', ], ], ]); 

Maybe I missed something or didn’t quite correctly understand what you want to achieve, but I advise you to read the documentation on the githaba , where everything is pretty well chewed up. Successes in studying.