Home > Net >  Symfony form validation: require field if another field is not empty
Symfony form validation: require field if another field is not empty

Time:12-17

I use Symfony 5.3. I have a form with 3 fields that are not mapped to any entity:

  • "reason" - text,
  • "use_predefined" - checkbox
  • "predefined_reason" - dropdown.

I build the form like this (a fragment):

...
public function build(FormBuilderInterface $builder)
{
    $builder->add('reason', TextareaType::class, [
        'label' => 'Reason',
        'required' => true,
        'mapped' => false,
    ]);
    $builder->add('use_predefined', 
        CheckboxType::class, [
        'label' => 'Use predefined reason',
        'required' => false,
        'mapped' => false,
    ]);
    $builder->add(
        'predefined_reason',
        ChoiceType::class,
        [
            'choices' => [
                'option 1' => 1,
                'option 2' => 2,
                'option 3' => 3,
                'option 4' => 4,
            ],
            'expanded' => false,
            'mapped' => false,
            'label' => 'some label',
            'required' => false,
        ]
    );
}
...

"reason" field should displayed in the UI as required, but other two should not. However during the validation if checkbox "predefined_reason" is checked, the first field should not be required, and "predefined_reason" - should.

CodePudding user response:

You should be able to use Expression to assert if your property are valid.

/**
 * @Assert\Expression(
 *     "(this.getUsePredefined() == true) or (this.getUsePredefined() == false and this.getReason() != null)",
 *     message="UsePredefined is not checked so reason is required"
 * )
 */
protected $reason;


protected $use_predefined;

/**
 * @Assert\Expression(
 *     "(this.getUsePredefined() == true and this.getPredefinedReason() != null) or (this.getUsePredefined() == false)",
 *     message="Error message"
 * )
 */
protected $predefined_reason;

Don't forget to edit your form and remove required field if unnecessary since they will be verified in form validation.

If you want something more dynamic, you may have to use javascript.

You could also create a custom contraint to do something similar.

  • Related