Confidence
Confidence

Reputation: 2303

Symfony2 Form: Tags Collection does not get persisted

I have an Upload Entity , that can have many Tags,

/**
 * @ORM\ManyToMany(targetEntity="Tag", mappedBy="uploads")
 */
protected $tags;

and a Tag can be in Many Uploads

/**
 * @ORM\ManyToMany(targetEntity="Upload", inversedBy="tags")
 * @ORM\JoinTable(name="upload_tag")
 */
protected $uploads;

i have a Form, where i can upload a file, and select tags with multi-select....here is a snippet from the UploadType file

......other form elements.....
$builder->add('tags', 'entity', array(
    'multiple' => true,
    'property' => 'name',
    'class' => 'BoiMembersBundle:Tag',
));

The forum submits fine, without errors.....but when i look into my upload_tag, which represents the ManyToMany relationship in my mysql DB, i see no new lines!!!

So the application does not report any errors what so ever..other form elements of Upload get insterted fine, and forwards to the "success"-Route, but i do not see persistanse for the tags.

Upvotes: 0

Views: 552

Answers (1)

gremo
gremo

Reputation: 48909

It's because Upload it's not the owner of the relation with Tag and you're persisting Upload with new entities (of Tag type) inside the relation itself. In fact, it has the mappedBy attribute.

You can configure the cascade option:

/**
 * @ORM\ManyToMany(targetEntity="Tag", mappedBy="uploads", cascade={"persist"})
 */
protected $tags;

Or make Upload the owner of the relation (if you think you'll never persist Tag entity with a new Upload inside it):

class Upload
{
    /**
     * BIDIRECTIONAL - OWNING SIDE
     * @ORM\ManyToMany(targetEntity="Tag", inversedBy="uploads")
     * @ORM\JoinTable(name="upload_tag")
     */
     protected $tags;
}    

class Tag
{

    /**
     * BIDIRECTIONAL - INVERSE SIDE
     * @ORM\ManyToMany(targetEntity="Upload", mappedBy="uploads")
     */
     protected $uploads;
}

See Working with Associations on Doctrine 2.x documentation.

Upvotes: 1

Related Questions