2

I have the following code in use in gridview and it's working perfectly:

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

This displays all the item's categories on new row within the table cell. However if I want to display something similar in DetailView, it's not working. Detailview gives me an error:

Object of class Closure could not be converted to string

So how is it possible to access has_many relations in DetailView?

The relation is the following:

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

2 Answers 2

2

DetailView doesn't accept a callable as 'value'. You need to either calculate the string before you call the 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(),

You can even put the function inside the model class you are using with the DetailView and just call it from there.

1
0

You "can" use a function in DetailView as follows:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.