Set Date Ranges on Symfony2 Forms

Recently I was trying to render birth dates forms for a given entity and usually ages go way back than what is hard coded in sf2 which is +5/-5 years. So I went in and dug a little bit on the documentation, but it was not very clear how to set the ranges to custom.
So I went straight into the code here and found how to turn my:

->add('dob', 'date')

Into:

->add('dob', 'date', array(
    'years' => range(date('Y') - 100, date('Y') - 20)
   )
)

For more ranges we can check the link above:

public function getDefaultOptions(array $options)
{
    return array(
        'years'         => range(date('Y') - 5, date('Y') + 5),
        'months'        => range(1, 12),
        'days'          => range(1, 31),
        'widget'        => 'choice',
        'input'         => 'datetime',
        'format'        => \IntlDateFormatter::MEDIUM,
        'data_timezone' => null,
        'user_timezone' => null,
        'empty_value'   => null,
        // Don't modify \DateTime classes by reference, we treat
        // them like immutable value objects
        'by_reference'  => false,
    );
}

4 thoughts on “Set Date Ranges on Symfony2 Forms

  1. It is horrible UX to let the user select a year from a drop down. I’ve created this bundle
    (https://github.com/Happyr/BirthdayBundle) to make sure you type a year and select month and day. It is a good start and it might be improved.

    @Hurricane: 30 februari will case validation error. If it is important for you that the user cant select invalid dates you may solve it by using javascript.

Leave a Reply to Michael Holm Cancel reply

Your email address will not be published. Required fields are marked *