使用Yii2,我正在尝试创建一个detailView。我想隐藏空行,因此我使用kartik-v detailview。但是,如果属性符合某个条件,我也想隐藏属性。所以我偶然发现了this这个问题,这个问题抓住了我的问题的意图。但是,它并不能令人满意。 (This question问大致相同的事情)。一个例子
<?= DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => [
'id',
'name', //cant be null, always shown
'description:ntext', //can be null, so hidden thanks to kartiks detailview
isAdmin() ? "password" :"", //an example, of course
"hypotheticalOtherField",
isAdmin() ? [
'attribute'=>'client',
'format'=>'raw',
'value'=>function($object) {
return Html::button("MyButton".$object->client);
}
] : ""
]
]) ?>
正如您所看到的,我想基于(在此示例中)用户是否为admin来显示一些字段。遗憾的是,如果不满足条件,则将emtpy字符串,空数组或空值插入到属性数组中会产生错误(插入空字符串时IE The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"
)
我想我可以像这样创建属性数组:
$attrs = ['id','name','description:ntext'];
if (isAdmin()) array_push($attrs, "password");
array_push($attrs, "hypotheticalOtherField");
if (isAdmin()) array_push($attrs, [
'attribute'=>'client',
'format'=>'raw',
'value'=>function($object) {
return Html::button("MyButton".$object->client);
}
]);
echo DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => $attrs
]);
但随后严重破坏了标准Yii2代码布局的概述。
那么有没有办法有条件地将值插入数组中,所以我可以继续编码Yii风格:estetic,有条理,整洁?或者也许在创建视图时应跳过Yii2知道它的值
答案 0 :(得分:3)
您可以visible
使用DetailView
<?= DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => [
'id',
'name', //cant be null, always shown
'description:ntext', //can be null, so hidden thanks to kartiks detailview
[
'visible' => (isAdmin() ? true : false),
'value' => $model->password,
'label' => 'test'
],
]) ?>
添加您要添加的任何条件!在visible
答案 1 :(得分:1)
如果你尝试使用数组附加速记,代码的外观更像yii2 Stylish
基于数组的属性是一种正确的(好)练习。
$attrs[] = ['id','name','description:ntext'];
if (isAdmin()) {
$attrs[] = ['password'];
}
$attrs[] = ['hypotheticalOtherField']
if (isAdmin()) {
$attrs[] = [
'attribute'=>'client',
'format'=>'raw',
'value'=>function($object) {
return Html::button("MyButton".$object->client);
}
}
echo DetailView::widget([
'hideIfEmpty' => true, //available in kartik's detailview
'model' => $model,
'attributes' => $attrs
]);