Description
Symfony version(s) affected: 4.2.7
Description
I'm not sure this is a bug. It might be a simple question, but surely about a behavior I consider like weird.
In some Form, in some EntityType
with 'multiple' => true
, if you interfer with the query_builder
and call setMaxResults(x)
on the builder, then x
will also enter in validation flow: the form field will be invalid if the number of submitted entities is greater than x
.
How to reproduce
Let's consider this:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('authors', EntityType::class, [
'required' => false,
'class' => User::class,
'query_builder' => function (EntityRepository $r) {
return $r
->createQueryBuilder('user')
->setMaxResults(2)
;
},
;
}
From this point, nothing stops the frontend from sending more than 2 entities. You could imagine Select2 field with its own AJAX request. And this will lead to the form being invalid.
One could argue this makes no sense to limit the query to 2 results then sending 3 entities. While I could agree with this, my concern is not about the logic behind the behavior, but the fact that I think it's not the role of the query_builder
option to define parallel constraints on its way or have any influence upon form validation. It is not documented, it raises very generic error messages, in one word it is rather unpredictable.
Possible Solution
If it's a bug, well it's a bug, happy for having reported it. I did not have any time to dig into the code and understand the behavior, though, so I did not come out with a fix. I could try finding some time for this if you ask. (:
If it's a wanted behavior, I won't debate the choice itself, but I think it could be better documented or at least raise a more accurate error message on the form field.