Iter Ator
Iter Ator

Reputation: 9324

How is it possible to fill a OneToMany relationship with new entities in Symfony forms?

I would like to create a form for my entity named Order:

/** @ORM\Entity */
class Order {
    //...
    /**
     * @ORM\OneToMany(targetEntity=Entry::class, mappedBy="order", orphanRemoval=true)
     */
    private $entries;
    //...
}

The Entry class looks like this:

/** @ORM\Entity */
class Entry {
    //...
    /**
     * @ORM\ManyToOne(targetEntity=Product::class)
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;

    /**
     * @ORM\Column(type="integer")
     */
    private $count = 0;
    //...
}

I already defined a type for Entry.

An Order has multiple Entry. I would like to make it possible to create the entries in the same form, where the Order is created. I can not use EntityType with 'multiple' => true, because the Entry instances do not exist before the Order.

Upvotes: 1

Views: 867

Answers (2)

Julien FOURNIER
Julien FOURNIER

Reputation: 107

You can use CollectionType::class to embed another form. Create a EntryType form and add it to your OrderType form with a CollectionTypefield. Add a allow_add property and check the docs to find how to display the Form.

If you want to persist/flush all entities, you have to add a `cascade={'persist'} to your relation.

Upvotes: 2

Florent Cardot
Florent Cardot

Reputation: 1418

This can be easily done by symfony using embedded form.

There are a lot to say about how to use it, so here are :

Fully example step by step of how to do it from entity creation to html implementation

The symfony cookbook : How to Embed a Collection of Forms

And symfony doc : How to Embed a Collection of Forms

Upvotes: 1

Related Questions