Yii2 如何在Yi2 ActiveForm中内爆数组以在文本框中显示它?
子字段是mongoDB中的数组:Yii2 如何在Yi2 ActiveForm中内爆数组以在文本框中显示它?,yii2,active-form,Yii2,Active Form,子字段是mongoDB中的数组: <?= $form->field($model, 'children') ?> 我需要使用内爆(“,”,$model->children)不知何故,如何在活动表单中使用它?现在该怎么办 解决办法是什么?如何将该数组转换为字符串?在$form->field()调用中使用时,将显示$model->children属性的内容。如果属性的内容是一个数组,并且希望/需要它是一个字符串,则必须在调用field()之前转换内容 所以像这样,它可能会起作用
<?= $form->field($model, 'children') ?>
我需要使用内爆(“,”,$model->children)
不知何故,如何在活动表单中使用它?现在该怎么办
解决办法是什么?如何将该数组转换为字符串?在$form->field()
调用中使用时,将显示$model->children
属性的内容。如果属性的内容是一个数组,并且希望/需要它是一个字符串,则必须在调用field()
之前转换内容
所以像这样,它可能会起作用
<?php
$model->children = implode(',', $model->children);
echo $form->field($model, 'children');
?>
不确定编辑这样的列表值(在文本字段中)是最好的方法。保存时必须将字符串重新分解。但上面的代码是将该数组转换为字符串的解决方案。因为我想在每个小部件、网格视图中将其转换为字符串,所以我在模型中使用了afterFind()
函数将其转换为字符串。现在一切看起来都很棒:
public function afterFind() {
parent::afterFind();
if (is_array($this->children)) {
$this->children = implode(',', $this->children);
}
}
此解决方法会导致不同的视图中出现重复的代码。我在我的核心模型中通过afterFind()
解决了这个问题,以便首先返回字符串+谢谢。
public function afterFind() {
parent::afterFind();
if (is_array($this->children)) {
$this->children = implode(',', $this->children);
}
}