2

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!

Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
punckle
  • 23
  • 6
  • I don't think it's possible. According to [this](https://api.jqueryui.com/datepicker/#option-maxDate) you can only set the `maxDate` in initialization of the plugin with a json object or after by setting the `maxDate` `option`. – alexcm Aug 11 '21 at 14:05
  • 1
    I guess you could modify your form DateType to add a `max` attribute (like [this](https://stackoverflow.com/a/55243265/13013725)), but it will probably keep showing all the dates in your frontend datepicker plugin. You have to modify the frontend to do this or modify the plugin so it can read this max and min attribute to create the `maxDate` and `minDate` options in the plugin. – alexcm Aug 11 '21 at 14:12

1 Answers1

4

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;
Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35