10

I get an error when I use a function to get the value of an attribute and it's working normally using Gridview. What I'm doing wrong?

<?= DetailView::widget([
    'model'      => $model,
    'attributes' => [
        [
            'label'  => 'subject_type',
            'value'  => function ($data) {
                return Lookup::item("SubjectType", $data->subject_type);
            },
            'filter' => Lookup::items('SubjectType'),
        ],
        'id',
        'subject_nature',
    ],
]) ?>
robsch
  • 9,358
  • 9
  • 63
  • 104
Deena Samy
  • 503
  • 2
  • 7
  • 20
  • From version 2.0.11 `value` may be also a function. See the ['docs'](http://www.yiiframework.com/doc-2.0/yii-widgets-detailview.html#$attributes-detail). – robsch Dec 15 '17 at 10:22

3 Answers3

15

I have experienced this kind of problem. The error was

PHP Warning – yii\base\ErrorException htmlspecialchars() expects parameter 1 to be string, object given

what I did was transfer the function in the model like this.

function functionName($data) {
     return Lookup::item("SubjectType", $data->subject_type);
},

and then in your view.php file..

  [
            'label'=>'subject_type',
            'value'=>$model->functionName($data),
  ],
beginner
  • 2,024
  • 5
  • 43
  • 76
15

Just use call_user_func()

<?= DetailView::widget([
    'model'      => $model,
    'attributes' => [
        [
            'label'  => 'subject_type',
            'value'  => call_user_func(function ($data) {
                return Lookup::item("SubjectType", $data->subject_type);
            }, $model),
            'filter' => Lookup::items('SubjectType'),
        ],
        'id',
        'subject_nature',
    ],
]) ?>
Alexey Berezuev
  • 785
  • 9
  • 27
13

Fabrizio Caldarelli, on 05 January 2015 - 03:53 PM, said: Yes because 'value' attribute is a real value or attribute name, as doc says

So your code should be:

<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        [
            'label'  => 'subject_type',
            'value'  => Lookup::item("SubjectType", $model->subject_type),
            'filter' => Lookup::items('SubjectType'),
        ],
        'id',
        'subject_nature',
    ],
]) ?>
robsch
  • 9,358
  • 9
  • 63
  • 104
Deena Samy
  • 503
  • 2
  • 7
  • 20