Yii2 DetailView: value of attribute using a functi

2020-04-07 12:02发布

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',
    ],
]) ?>

标签: php yii2
3条回答
老娘就宠你
2楼-- · 2020-04-07 12:17

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',
    ],
]) ?>
查看更多
Evening l夕情丶
3楼-- · 2020-04-07 12:23

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',
    ],
]) ?>
查看更多
聊天终结者
4楼-- · 2020-04-07 12:30

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),
  ],
查看更多
登录 后发表回答