Has_many Relationship in DetailView

I have the following code used in gridview and it works fine:

                    ['format' => 'raw',
                'label' => 'Categories',
                'value' => function ($data) {
                    $string = '';
                    foreach ($data['fkCategory'] as $cat) {
                        $string .= $cat->category_name . '<br/>';
                    }
                    return $string;
                }],

Shows all categories of elements in a new row in a table cell. However, if I want to display something like this in the DetailView, it does not work. Detailview gives me an error:

An object of class Closure cannot be converted to a string

So how can you access has_many's relationships DetailView?

The relationship is as follows:

    public function getFkCategory()
{
    return $this->hasMany(Categories::className(), ['category_id' => 'fk_category_id'])
        ->via('CategoryLink');
}
+2
source share
2 answers

DetailView does not accept the called value as "value". You need to either compute the string before calling DetailView:

$string = '';
foreach ($data['fkCategory'] as $cat) {
     $string .= $cat->category_name . '<br/>';
}
...
'value' => $string,

or create a function that does this:

function getCategories() {
    $string = '';
    foreach ($data['fkCategory'] as $cat) {
        $string .= $cat->category_name . '<br/>';
    }
    return $string;
}
...
'value' => getCategories(),

, DetailView, .

+2

"" DetailView :

'value' => call_user_func(function($model){
                              <your_code_here>
                        }, $model),
0

Source: https://habr.com/ru/post/1628494/


All Articles