Using hasmany in DetailView::widget

Hello, I am new to Yii(2) and have a problem using the DetailView::widget with a hasmany relation.


    <?= DetailView::widget([

        'model' => $model,

        'attributes' => [

            'id',

            'bookname',

            'bookDescrs.text',

        ],

    ]) ?>


  public function getBookDescrs()

    {

        return $this->hasMany(BookDescr::className(), ['id_book' => 'id']);

    }

The books have descriptions in several languages and i want to display the description in every language in the detailview.

but all i get is: Text: not set

what is the right approach to realize this

"BookDescrs" is an array. So you have to access "BookDescrs[$i].text" where $i is the index to the array.

Thanks for your answer, but if i use:


  <?= DetailView::widget([

        'model' => $model,

        'attributes' => [

            'id',

            'bookname',

            'bookDescrs[0].text',

        ],

    ]) ?>

i get the following error:


Invalid Configuration – yii\base\InvalidConfigException

The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"

i also dont know how to loop all the entries into the DetailView

try following:


  <?= DetailView::widget([

        'model' => $model,

        'attributes' => [

            'id',

            'bookname',

            [

                'attribute' => 'bookDescrs',

                'valeu' => $model->bookDescrs[0].text

            ]

        ],

    ]) ?>




<?= DetailView::widget([

    'model' => $model,

        'attributes' => [

            'id',

            'bookname',

            [

                'attribute' => 'bookDescrs',

                'value' => $model->bookDescrs[0]->text,

            ]

        ],

    ]) ?>



The above code will show only the first description. And it may give you an error when the book accidentally has no descriptions at all.

One thing you can do is creating a getter method to bring back all the descriptions:




// in your Book model

public function getDescriptionText()

{

    $texts = [];

    foreach($this->bookDescrs as $descr) {

        $texts[] = $descr->text;

    }

    return implode("\n", $texts);

}



And you can use it in the DetailView:




<?= DetailView::widget([

    'model' => $model,

        'attributes' => [

            'id',

            'bookname',

            [

                'attribute' => 'bookDescrs',

                'value' => $model->getDescriptionText(),

                // or 'value' => 'descriptionText',

            ]

        ],

    ]) ?>



Please refer to the API documentation for DetailView::attributes

http://www.yiiframework.com/doc-2.0/yii-widgets-detailview.html#$attributes-detail