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);