Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Dynamic Form Constraints

Tags:

symfony

Looking for a straightforward way to add constraints dynamically to all of my form fields. So far I've hit upon the idea of using a form type extension, which kind of works: I can modify the form view and then manually check the view on form submission.

However, is there a smarter way to add real Symfony-based constraints in real-time?

(Note that the constraints need to be added to the form in real-time as the form loads based on user configuration in the database.. Predefined form groups and the like won't work.)

like image 751
nurikabe Avatar asked Oct 20 '25 11:10

nurikabe


1 Answers

I would suggest to use form events.

Use the PRE_SUBMIT event to edit the form before validation.

Recreate your fields with $event->getForm()->add(...) adding your constraints.

Of course you can automatically add the listener to all form using a FormExtension which adds the listener.

EDIT : Some examples from Alsatian67/FormBundle


Your extension should looks like :

class ExtensibleExtension extends AbstractTypeExtension
{
    private $extensibleSubscriber;
    public function __construct($extensibleSubscriber) {
        $this->extensibleSubscriber = $extensibleSubscriber;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Only apply on base form
        if($builder->getForm()->isRoot())
        {
            $builder->addEventSubscriber($this->extensibleSubscriber);
        }
    }

    public function getExtendedType()
    {
        return FormType::class;
    }
}

And your EventListener / EventSubscriber should iterate on all the children :

foreach($event->getForm()->all() as $child){
    $childName = $child->getName();
    $type = get_class($child->getConfig()->getType()->getInnerType());
    $options = $child->getConfig()->getOptions();

    $options['constraints'] = array(/* ... */);

    $form->add($childName,$type,$options);
}
like image 175
Alsatian Avatar answered Oct 24 '25 05:10

Alsatian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!