A
A
Andrey Zanovsky2014-04-26 16:20:46
symfony
Andrey Zanovsky, 2014-04-26 16:20:46

Symfony2: How to validate a form collection?

There is the essence of contests and there is the essence of prizes. In the prizes there are fields "place" and "prize name".
Entities are connected by a one-to-many relationship.
The essence of competitions

/**
     * @ORM\OneToMany(targetEntity="Prize", mappedBy="contest", cascade={"persist"})
     *
     */
    protected $prizes;

Essence of prizes
/**
     * @ORM\ManyToOne(targetEntity="Contest", inversedBy="prizes")
     * @ORM\JoinColumn(name="contest_id", referencedColumnName="id")
     */
    protected $contest;

And there is a form in which to create a contest, in which you can add any number of prizes, but the "place" and "prize name" fields should not be empty.
In the essence of prizes, I added @Assert \NotBlank() annotations, but this did not help, when submitting the form, there is no message that the field cannot be empty, but an error appears saying that name=NULL cannot be saved in the database.
Then I found this article symfony.com/doc/current/reference/constraints/Coll... and added the following thing to the essence of the competition
/**
     * @ORM\OneToMany(targetEntity="Prize", mappedBy="contest", cascade={"persist"})
     * @Assert\Collection(
     *     fields = {
     *         "place" = @Assert\NotBlank(),
     *         "name" = @Assert\NotBlank(),
     *     },
     *     allowMissingFields = true
     * )
     *
     */
    protected $prizes;

In this case, in any scenario (whether the required fields are filled in or not), the message "This field was not expected" is displayed.
How to properly validate the fields I need?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BoShurik, 2014-04-30
@andrei_z

symfony.com/doc/current/reference/constraints/Vali...

B
Boris Benkovsky, 2014-04-26
@benbor

If you are using FormType then look this way stackoverflow.com/questions/10138505/symfony2-vali...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question