Answer the question
In order to leave comments, you need to log in
DetailView and GridView. Displaying the name of the line in related tables. Yii2?
Please tell me, otherwise I broke my whole head.
I have 2 tables: one with courses (course) and the other with authors (author).
I'm in the "Course" in view () - in the form I display a list of course authors:
<?php $authors = \common\models\Author::find()->where(['status' => 1])->all();
$items = \yii\helpers\ArrayHelper::map($authors,'id','name');
$params = ['prompt' => '--- Укажите автора ---'];
echo $form->field($model, 'author',['options' => ['class' => 'col-xs-2']])->dropDownList($items,$params);
?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
[
'attribute' => 'category_id',
'value' => function($data){
return $data->category->name;
},
],
'name',
'content:raw',
[
'attribute' => 'author',
'value' => function($model){
return $model->author->name;
},
],
'description',
[
'attribute' => 'statusName',
'value' => function($model) {
return Html::tag('span',
$model->getStatusName(),
['class' => 'label label-' . ArrayHelper::getValue([0 => 'danger', 1 => 'success'], $model->status_id)]
);
},
'format' => 'raw',
],
'smallImage:image',
],
]) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'class' => 'yii\grid\ActionColumn',
'header' => 'Действия',
'options' => ['width' => '10']
],
[
'attribute' => 'category_id',
'value' => function ($data) {
return $data->category->name;
},
'options' => ['width' => '200']
],
'name',
[
'attribute' => 'author',
'value' => function ($data) {
return $data->author->name;
},
'options' => ['width' => '200']
],
'smallImage:image',
[
'attribute' => 'status_id',
'filter' => \common\models\Course::getStatusList(),
'value' => 'statusName',
],
],
]); ?>
public function getCourse()
{
return $this->hasMany(Course::className(), ['author' => 'id']);
}
public function getAuthor()
{
return $this->hasOne(Author::className(), ['id' => 'author']);
}
Answer the question
In order to leave comments, you need to log in
Good evening.
These two lines must be moved to a separate method.
$authors = \common\models\Author::find()->where(['status' => 1])->all();
$items = \yii\helpers\ArrayHelper::map($authors,'id','name');
$query = Author::find()->with('course');
// далее подставляете это в ActiveDataProdiver
'value' => function ($model) {
return $model->author->name;
},
'value' => 'author.name'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question