Symfony2中的CollectionType验证

I spent a lot of time to find a solution to this problem but I don't find the correct solution

I have a User entity that can contain multiple entity Address. The validation of the User entity should function like this:

  • User must have at least two entities Address
  • User must have a maximum of three entities Address
  • Address has its own validation constraints

Both entities have their formType and Address is a CollectionType in User formType.

Currently, I create in my User controller, 3 Address that appear correctly in the view. I use 'Assert\Count' with 'min=2' to validate the form in the entities. In my controller, I filter the query to remove the Address which have not been completed, then I validate the form. This approach is not correct. I am unable to display the 3 addresses if the form is not valid, I have only the addresses that have been completed. In addition, errors are not available in the fields when I made ​​the view with Twig

Ideally logic would be as follows: the Address are validated and only the valid Address are taken into account by User. User checks its validation constraints are respected then the User entity is stored in the database. Simple, right ? (... well that's what I thought)

Do you have any ideas or blog posts that cover my problem?

EDIT (to answer question in comment)

In the User entity

<?php
//...
* @Assert\Count(
*      min=2,
*      minMessage="user_form_not_enough_addresses",
*      max=3,
*      maxMessage="user_form_too_much_addresses"
* )
*/
private $addresses;
//...

In the User controller (when I filter the request)

//...

// Removing not completed addresses from request
$this->_filterRequest($request);

$userType = new UserType();
$user = new User();

$userForm = $request->get($userType->getName());
foreach ($userForm['addresses'] as $address) {
    $user->getAddresses()->add(new Address());
}

$form = $this->createForm($userType, $user);
$form->bind($request);

After some research the only acceptable solution was to use Symfony events.

We must distinguish between two parts: validation and data recording. In both parts, you must validate addresses using the validator and do something based on errors that are found.

In the case of validation, you must copy the file validation ValidationListener.php then use the services to match your file. Then simply customize the validation mechanism. The objective is to only display addresses that are not valid but that are required or not required but with some fields that are filled, just search the different cases and use ViolationMapperInterface::mapViolation() when the error should be displayed.

In the case of data recording, just filter invalid addresses to be sure they are not taken into consideration by Doctrine (which would cause an SQL error otherwise)