Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically control the validation of a form?

I've got some issues with Symfony's form validation handling. I'd like to validate a form bound to an entity based on its data. There are quite a bunch of information how to dynamically modify the form fields using FormEvents. What I'm missing on this topic is how to control/modify the validation.

My simplified use case is:

  1. A user can add an event to a calendar.
  2. The validation checks if there's already an event.
  3. If there's a collision, the validation will throw an error.
  4. The user should now be able to ignore this error/warning.

The validation is implemented as a Validator with Constraint::CLASS_CONSTRAINT as the target (as it's taking some more stuff into account).

I tried to:

  • Hack around the validation groups, but couldn't find access to the entity wide validators.
  • Hack around the FormEvents and add an extra field like "Ignore date warning".
  • Hack around the submit button to change it to something like "Force submit".

... but never found a working solution. Even simpler hacks with a single property based validator didn't work out. :(

Is there a Symfony way to dynamically control the validation?

Edit: My code looks like this:

use Doctrine\ORM\Mapping as ORM;
use Acme\Bundle\Validator\Constraints as AcmeAssert;

/**
 * Appointment
 *
 * @ORM\Entity
 * @AcmeAssert\DateIsValid
 */
class Appointment
{
  /**
   * @ORM\Column(name="title", type="string", length=255)
   *
   * @var string
   */
  protected $title;

  /**
   * @ORM\Column(name="date", type="date")
   *
   * @var \DateTime
   */
  protected $date;
}

The validator used as a service:

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
 * Validates the date of an appointment.
 */
class DateIsValidValidator extends ConstraintValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($appointment, Constraint $constraint)
    {
        if (null === $date = $appointment->getDate()) {
            return;
        }

        /* Do some magic to validate date */
        if (!$valid) {
            $this->context->addViolationAt('date', $constraint->message);
        }
    }
}

The corresponding Constraint class is set to target the entity class.

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class DateIsValid extends Constraint
{
    public $message = 'The date is not valid!';

    /**
     * {@inheritdoc}
     */
    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

    /**
     * {@inheritdoc}
     */
    public function validatedBy()
    {
        return 'acme.validator.appointment.date';
    }
}

Edit 2: Try with FormEvents... I also tried all the different events.

$form = $formFactory->createBuilder()
    ->add('title', 'text')
    ->add('date', 'date')
    ->addEventListener(FormEvents::WHICHONE?,  function(FormEvent $event) {
        $form = $event->getForm();

        // WHAT TO DO HERE?
        $form->getErrors(); // Is always empty as all events run before validation?

        // I need something like
        if (!$dateIsValid) {
            $form->setValidationGroup('ignoreWarning');
        }
    });

Edit 3: Constraint are correctly declared. That's not the issue:

services:
    validator.acme.date:
        class: AcmeBundle\Validator\Constraints\DateValidator
        arguments: ["@acme.other_service"]
        tags:
            - { name: validator.constraint_validator, alias: acme.validator.appointment.date }
like image 817
althaus Avatar asked Jun 20 '14 10:06

althaus


People also ask

Which method is used to add dynamic validation to the forms?

The FormGroup class exposes an API that enables us to set validators dynamically. We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.

What is dynamic validation?

Dynamic Validation validates Snap properties as you enter them. SnapLogic starts validating a property as you edit it; a preview of the result of this validation is displayed and updated as you continue editing.

How do I add custom validators dynamically in reactive form?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.


2 Answers

Validation is done on the entity, all Forms does is execute the Object's validations. You can choose groups based on submitted data

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => function(FormInterface $form) {
            $data = $form->getData();
            if (Entity\Client::TYPE_PERSON == $data->getType()) {
                return array('person');
            } else {
                return array('company');
            }
        },
    ));
}

I have had issues when using this approach on embedded forms && cascade-validation

Edit: using flash to determine if validation must take place.

// service definition
    <service id="app.form.type.callendar" class="%app.form.type.callendar.class%">
        <argument type="service" id="session" />
        <tag name="form.type" alias="my_callendar" />
    </service>


// some controller
public function somAvtion() 
{
    $form = $this->get('app.form.type.callendar');
    ...
}

// In the form
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => function(FormInterface $form) {
            $session = $form->getSession();
            if ($session->getFlashBag()->get('callendar_warning', false)) {
                return array(false);
            } else {
                return array('Validate_callendar');
            }
        },
    ));
}
like image 199
juanmf Avatar answered Oct 16 '22 16:10

juanmf


How does your user interact with the application to tell it to ignore the warning? Is there some kind of additional button? In that case you could simply check the button used for submitting the form or add some kind of hidden field (ignore_validation) etc. Wherever you end up getting that user input from (flash and dependency injection, based on submitted data etc.), I would then use validation groups and a closure to determine what to validate (just like juanmf explained in his answer).

RE your second approach (Form Events), you can add a priority to event listeners: As you can see in Symfony's Form Validation Event Listener, they use FormEvents::POST_SUBMIT for starting the validation process. So if you just add an event listener, it gets called before the validation listener and so no validation has happened yet. If you add a negative priority to your listener, you should be able to also access the form validation errors:

$builder->addEventListener(FormEvents::POST_SUBMIT, function(){...}, -900);
like image 20
Iris Schaffer Avatar answered Oct 16 '22 16:10

Iris Schaffer