symfony-console-form icon indicating copy to clipboard operation
symfony-console-form copied to clipboard

Doctrine Collection support

Open secit-pl opened this issue 4 years ago • 1 comments

I found that the bundle have problems when dealing with Doctrine\Common\Collections\Collection (ArrayCollection). On local test instance I have found that the problem is here:

Matthias\SymfonyConsoleForm\Bridge\Transformer\AbstractTransformer::defaultValueFrom

    protected function defaultValueFrom(FormInterface $form)
    {
        $defaultValue = $form->getData();
        if (is_array($defaultValue)) {
            $defaultValue = implode(',', $defaultValue);
        }

        return $defaultValue;
    }

after changing it to:

    protected function defaultValueFrom(FormInterface $form)
    {
        $defaultValue = $form->getData();
        if (is_array($defaultValue)) {
            $defaultValue = implode(',', $defaultValue);
        } elseif ($defaultValue instanceof Collection) {
            $defaultValue = implode(',', $defaultValue->toArray());
        }

        return $defaultValue;
    }

the Collection is handled properly and even form type Symfony\Bridge\Doctrine\Form\Type\EntityType is working very well.

Could you please look at this and apply the patch if the solution is valid?

secit-pl avatar Apr 09 '21 19:04 secit-pl

I much prefer that you do it. I can add a test if you like, but can you make a PR that adds an example using a form with a collection? Also, I wonder if it's possible to generalize this, e.g. shouldn't any iterable just work? Finally, the assumption here is that the toArray() returns an array of strings or stringable values. I think that needs to be verified before we call implode() (same for the is_array() branch above by the way).

matthiasnoback avatar Apr 14 '21 06:04 matthiasnoback