1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This workaround cause duplicate codes in different views file. I solved it by afterFind() in my core model in order to return string in the first place. +1 thanks.
0

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);
        }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.