Search code examples
symfonydatesonata-adminsonata

Sonata Date range


I have a small issue I am working on a small project using Sonata but I am trying to figure out how to customize the date range which a person can choose a date, example from 1 January 2000 to 31 December 2020. Could someone tell me where I can find it in the Sonata documentation or show me how to do it ? Because I have a little look and I have nothing to completely customize the choice of dates.

Thanks in advance

Edit :

In symfony documentation I found this

'days' => range(1,31)

Here : http://symfony.com/doc/current/reference/forms/types/date.html

But I can't found anything in the sonata doc. And not working like on Symfony :/


Solution

  • I assume you use sonata_type_date_picker field in Sonata. Documentation is here. Then your case can be implemented like this:

    ->add('userDate', 'sonata_type_date_picker', [
        'dp_min_date' => 'Jan 1, 2000', //todo: date format here depends on your setup. Basicly it's the same format, you see in text field after you selected data in datepicker.
        'dp_max_date' => 'Dec 31, 2020',
    ]);
    

    Alternatively you can have date selector with 3 dropdowns - it's standard Symfony date field, works fine with SonataAdmin:

    ->add('userDate', 'date', [
        'years' => range(2000, 2020),
    ]);
    

    I would also recommend to add backend validation with the same rules (in Entity):

    /**
     * @var \DateTime()
     *
     * @Assert\Range(
     *      min = "2000-01-01",
     *      max = "2020-12-31"
     * )
     */
    protected $userDate;