Php – How to map symfony2’s form collection field to a doctrine’s array type field

doctrineformsPHPsymfony

I have form (AbstractType) that maps to a (doctrine-persisted) entity.

That entity has got a field which is of doctrine's type array.

According to symfony's docs it should be possible to map a form collection field to a PHP's array, but apparently it does not work when the form is mapped to an entity. Symfony expects that field to be a relation, but it is merely an array.

This is not actual code, just an example:

Consider this (doctrine-persisted) entity:

class Article
{
   ...
    /**
     * @ORM\Column(type="array")
     */
    protected $tags;   
   ...
}

And this entity (not managed by doctrine):

class Tag
{
   ...
    public $name;
   ...
}

And this form type:

class ArticleType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('tags', 'collection', array('type' => new TagType()));
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => '\Entity\Article',
        );
    }
}

Tag's form type:

class TagType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('name', 'text');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => '\Entity\Tag',
        );
    }
}

When trying to instantiate the ArticleType doctrine will complain something along the lines:

Expected argument of type "\Entity\Tag", "array" given

In file:

vendor/symfony/src/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php at line 47

Is it even possible to do what I want without writing my own field type?

UPDATE: Maybe I should rephrase my question: How do I tell symfony not to map this field to anything (if I change its name symfony complains that the entity doesn't have such property)?

Best Answer

I missed one thing. I had fixtures loaded which contained array of associative arrays in the collection property (tags here). I forgot to reload the fixtures after changing them to array of entities (array of Tag instances here).

Now everything works flawlessy, so ineed symfony can map a form collection both to an array and a relation (ArrayCollection). The difference is - I don't have to manually persist the inverse side of the relation.

So this was my bad. Thanks anyway.

Related Topic