Symfony validation/comparison between two dates in a form

Viewed 520

So I want to create a form with two dates. I want those dates to have constraints, that check if one of each is bigger than the other. This way I can get a valid time span.

I build a custom FormType like this:

class MainFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add( 'date_from', DateType::class, [
                'constraints' => [
                    new Assert\NotBlank()
                ]
            ])
            ->add( 'date_to', DateType::class, [
                'constraints' => [
                    new Assert\NotBlank(),
                    new Assert\GreaterThanOrEqual([
                        'value' => $builder->get('date_from'),
                        'message' => 'datepickers.to_less_than_from'
                    ])
                ]
            ]);
    }
}

At this point symfony does not throw an error, but the validation wont work either.

Is there any way to compare two dates, that are located in the same form, via Symfonys validator?

1 Answers

You can do this with this code

->add('dateToPublish', DateTimeType::class, array(
    'label' => 'notifications.date_to_publish',
    'required' => true,
    'widget' => 'single_text',
    'constraints' => [
        new NotBlank(),
        new DateTime(),
    ]))
->add('dateToEnd', DateTimeType::class, array(
    'label' => 'notifications.date_to_end',
    'required' => true,
    'widget' => 'single_text',
    'constraints' => [
        new NotBlank(),
        new DateTime(),
        new GreaterThan([
            'propertyPath' => 'parent.all[dateToPublish].data'
        ]),
    ]));

As you can see I'm making a constraint on dateToEnd to be greater than dateToPublish

Hopes this helps you

Related