Symfony Validation Trick: Dependent Validation

The trick happens here: we have to use this constraint not with static value, but with another field:namespace AppForm;use AppEntityBooking;use SymfonyComponentFormAbstractType;use SymfonyComponentFormExtensionCoreTypeDateType;use SymfonyComponentFormFormBuilderInterface;use SymfonyComponentOptionsResolverOptionsResolver;use SymfonyComponentValidatorConstraintsGreaterThan;use SymfonyComponentValidatorConstraintsNotBlank;use SymfonyComponentValidatorConstraintsDate;class BookingType extends AbstractType{ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('endDate', DateType::class, [ 'constraints' => [ new NotBlank(), new Date(), ] ]) ->add('startDate', DateType::class, [ 'constraints' => [ new NotBlank(), new Date(), new GreaterThan([ 'propertyPath' => 'parent.all[endDate].data' ]), ] ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Booking::class, ]); }}Render the form and try to enter wrong value:This trick is applicable only for Form Types and in case you are writing validation rules directly in entities, then follow example from official documentation.Read more about Forms in special article in Jobeet Tutorial.. More details

Leave a Reply