Search code examples
phpsymfonydate-rangeformbuilder

How to set DateType range from selected date to current date?


I want to create for that lets select year and month. Current solution doesn't work, I cuts all months to 7, as current month at this time of post is "7".

 $builder->add(
        'filter_date',
        DateType::class,
        [
            'format' => 'yMd',
            'years' => range(
                (new DateTime('2013-01-01'))->format('Y'),
                (new DateTime())->format('Y')
            ),
            'months' => range(
                (new DateTime('2013-01-01'))->format('m'),
                (new DateTime())->format('m')
            ),
            'days' => [1],
            'placeholder' => [
                'year' => '----',
                'month' => '----',
                'day' => false,
            ],
            'required' => true,
        ]
    )

How to make all years before to have 12 in month selection, and in current year, it won't be able to pick future months?


Solution

  • That is cause you are defining your interval for your month from january to the month of the current date with the awkward expression

    range(
                    (new DateTime('2013-01-01'))->format('m'),
                    (new DateTime())->format('m')
                )
    

    What about

    'months' => range(1,12)
    

    and simple for years if you want to go 5 years back

    'years' => range(date("Y")-5, date("Y"))
    

    or if you want 2013 as fixed start

    'years' => range(2013, date("Y"))
    

    ?

    The rendering of the input values is happened on the server side, so you are not able to dynamically add/remove values from the input. If you still want to use separated input values for choosing a date you have to write JS code your own to replace values dynamically.

    If you agree with a datepicker, you could use the following approach.

    'widget' => 'single_text',
    'attr' => array(
            'max' => date('Y-m-d')
        )