punckle
punckle

Reputation: 23

Disable a future date using the Symfony DateType

I'm using Symfony 5 and I have a problem with my form.

How to disable dates in the future when I use a DateType with 'widget' => 'single-text' and js-datepicker? Note that I don't have access to the frontend, everything has to be done in the backend. Here is what I currently have:

$builder->add('date', DateType::class, [
            'widget' => 'single_text',
            'attr' => [
                'class' => 'js-datepicker'
            ]
        ]);

Thank you in advance for your answer!

Upvotes: 2

Views: 1449

Answers (1)

Dhia Djobbi
Dhia Djobbi

Reputation: 1289

In case you want to use HTML5 validation you can use the max attribute:

$builder->add('date', DateType::class, [
    'widget' => 'single_text',
    'attr' => [
        'class' => 'js-datepicker',
        'max' => date('Y-m-d')
    ]
]);

And if you want to make a backend validation you can use Symfony Assert you can use LessThan or LessThanOrEqual (in case you want to include today date)

Inside your entity add this import:

use Symfony\Component\Validator\Constraints as Assert;

and then you can use @Assert :

/**
 * @Assert\LessThan("today")
 */
private $date;

Upvotes: 4

Related Questions