【发布时间】:2015-12-23 13:16:25
【问题描述】:
使用 Yii2,我正在尝试创建一个 detailView。我想隐藏空行,因此我使用了 kartik-v detailview。但是,如果属性符合特定条件,我也想隐藏它们。所以我偶然发现了this SO question,它抓住了我的问题的意图。然而,它的回答并不令人满意。 (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);
}
] : ""
]
]) ?>
如您所见,我想根据(在此示例中)用户是否为管理员来显示一些字段。可悲的是,如果不满足条件,将空字符串、空数组或空值插入属性数组会产生错误(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 风格的代码:美观、有条理、整洁?或者可能是 Yii2 知道在创建视图时应该跳过的值
【问题讨论】:
-
为什么觉得attributes数组不好,?您似乎只是一个代码样式问题....我发布了一个与 yii2 风格和良好实践一致的代码。看看你喜不喜欢
-
'我想隐藏空行,因此我使用 kartik-v detailview' - 你可以使用默认视图来完成,不需要第三方插件
-
@Coz 那么怎么做呢?我不能再使用 'hideIfEmpty' 属性,因为那是 kartiks 属性,但我使用 kartiks detailview 因为该属性