php Yii2 DetailView:使用函数的属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27787242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yii2 DetailView: value of attribute using a function
提问by Deena Samy
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?
当我使用函数获取属性值时出现错误,并且它使用 Gridview 正常工作。我做错了什么?
<?= 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',
],
]) ?>
回答by beginner
I have experienced this kind of problem. The error was
我遇到过这种问题。错误是
PHP Warning – yii\base\ErrorException
htmlspecialchars() expects parameter 1 to be string, object given
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..
然后在您的 view.php 文件中..
[
'label'=>'subject_type',
'value'=>$model->functionName($data),
],
回答by Alexey Berezuev
Just use call_user_func()
只需使用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',
],
]) ?>
回答by Deena Samy
Fabrizio Caldarelli, on 05 January 2015 - 03:53 PM, said: Yes because 'value' attribute is a real value or attribute name, as doc says
Fabrizio Caldarelli 于 2015 年 1 月 5 日 - 下午 03:53 说:是的,因为 'value' 属性是真实值或属性名称,正如 doc 所说
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',
],
]) ?>