Skip to content

Commit 0900bbf

Browse files
committed
Added callable validation_groups example
Recently I had a need to dynamically set the validation_groups of a small set of forms based on the user that was logged in. In digging about the FormValidator::resolveValidationGroups and saw I could use a class that implements the __invoke method. Figured I might as well write something about it and see if you'd want to add it to the docs.
1 parent 0fb7847 commit 0900bbf

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

book/forms.rst

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,57 @@ large or whether you tried to submit text in a number field.
621621

622622
.. _book-forms-type-reference:
623623

624+
625+
Groups based on a callable service
626+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
627+
628+
If you need some advanced logic to determine the validation groups that cannot
629+
be simply determined by a simple callback (for example that requires a few
630+
services) you can use a service. Implement a service that implements __invoke
631+
which accepts a FormInterface as a parameter.
632+
633+
use Symfony\Component\Form\FormInterface;
634+
635+
class ValidationGroupResolver
636+
{
637+
private $service1;
638+
private $sevice2;
639+
public function __construct($service1,$service2)
640+
{
641+
$this->service1 = $service1;
642+
$this->service2 = $service2;
643+
}
644+
645+
public function __invoke(FormInterface $form)
646+
{
647+
//figure out what groups to apply and return an array
648+
}
649+
}
650+
651+
Then in your form, inject the resolver and set it as the validation_groups.
652+
653+
use Symfony\Component\OptionsResolver\OptionsResolver;
654+
use Symfony\Component\Form\AbstractType
655+
656+
class MyClassType extends AbstractType
657+
{
658+
private $groupResolver;
659+
public function __construct($groupResolver)
660+
{
661+
$this->groupResolver = $groupResolver;
662+
}
663+
664+
// ...
665+
public function configureOptions(OptionsResolver $resolver)
666+
{
667+
$resolver->setDefaults(array(
668+
'validation_groups' => $this->groupResolver,
669+
));
670+
}
671+
672+
This will result in the FormValidator to invoke your group resolver to
673+
set the validation groups returned when validating.
674+
624675
Built-in Field Types
625676
--------------------
626677

0 commit comments

Comments
 (0)