当前位置: 动力学知识库 > 问答 > 编程问答 >

active form - How to implode an array to show it in a textbox in yii2 ActiveForm?

问题描述:

Children field is an array in mongoDB:

<?= $form->field($model, 'children') ?>

The error I get is:

Array to string conversion

I need to use implode(',', $model->children) somehow, how to use it in an ActiveForm? What to do now?

What is the solution? How to turn that array into a string?

网友答案:

The content of the $model->children attribute is displayed when being used in a $form->field() call. If the content of the attribute is an array and you want/need it to be a string you'll have to convert the content before the field() call.

So like this, it will probably work.

<?php    
$model->children = implode(',', $model->children);
echo $form->field($model, 'children');
?>

Not sure editing a list value like this (in a textfield) is the best way. You'll have to explode the string back when saving. But the code above is the solution to turn that array into a string.

网友答案:

As I wanted to turn it into string in every widget, grid view and so I used afterFind() function in my model in order to convert it into string. Now everything seems awesome:

public function afterFind() {
        parent::afterFind();
        if (is_array($this->children)) {
            $this->children = implode(',', $this->children);
        }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: