Showing related data with one to many relations via DetailView

Hi, everyone!

I need to display related data via DetailView or something like this.

The issue is that I need to displat related model which has many records belongs for parent one.

<?= DetailView::widget([


    'model' => $model,


    'attributes' => [


        'name',


        'relatedData.value',  // has many records which I need to display





    ],


]) ?>

Is that possible to do in widget like DetailView? And how exactly?

And how to edit this related data with parent record?

Maybe this information helps to understand what should be done.

I create a select element and fill it with options (adding and deleting options) which I should display and edit with this select.

Thanks in advance. :)

1 Like

Hi!

I’m working on a similar issue right now…

But have found no nice solution so far.

I guess you want to - like me - display the "Master" Model with multiple related "Slave" models in the same DetailView? Or would it be okay for you to have one DetailView for the "Master" and a seperate one for the "Slaves"?

As soon as I found a good solution I will post it here.

Regards

Okay…

What is working for me is following solution:




echo DetailView::widget([

    'model' => $model,

    'attributes' => [

        // attributes from the "parent" model

        'username',

        'created_at',

        'updated_at',


        // here I display related records as simple list in the detail view

        [

            'attribute' => 'someRelatedData', 

            'format'    => 'html',

            'value'     => call_user_func(function($model) 

            {

                $items = "";

                foreach ($model->relatedData as $related) {

                    $items .= $related->myValue."<br>";

                }

                return $items;

            }, $model)

        ],


    ],

]);



Maybe that is not what you are looking for…

but maybe it can give you a hint how to solve your issue.

Regards