Majesty
Majesty

Reputation: 1919

Symfony 2.8: CollectionType - do not delete old entries

I want to submit a form, each time I want a new entries being added to a database, but do not delete old ones.

Let's say I have an inventory entity, which contains a serial numbers collection.

Inventory form builder

$builder
    ->add('quantity', IntegerType::class)
    ->add('inventorySerialNumbers', CollectionType::class, array(
        'entry_type' => InventorySerialNumberType::class,
        'allow_add' => true,
        'allow_delete' => false,
        'by_reference' => false,
    ))
;

Inventory serial number property:

/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="InventorySerialNumber", mappedBy="inventory", cascade={"persist"})
 */
protected $inventorySerialNumbers;

So, I want to create a new inventory - I send a quantity and 2 inventorySerialNumbers and all data is being added correctly. But if I want to add one more entry, I will send a quantity 1 and one inventorySerialNumbers item, as a result I will get only one latest entry stored in the database.

Seems that Symfony ignoring cascade={"persist"} and 'allow_delete' => false

Upvotes: 1

Views: 760

Answers (1)

Stephan Vierkant
Stephan Vierkant

Reputation: 10174

A Form action will add or modify an entity. In this case, I think you're overwriting an entity instead of creating a new one (option 1) or modifying an existing one (option 2).

Option 1: add new items only

Create a simple form that will add a Inventory. A user will fill in the form and creates a new Inventory. After submitting the form, you will end up with two records in your database. If you want to know how many items you have, you have to sum up those values.

Option 2: allow users to modify items

If you want to allow your users to delete serial numbers or lower the quantity, you'll havo to create a editAction. Unfortunately I couldn't find a good example on Symfony's website, but here are two recources you should look at:

Upvotes: 1

Related Questions