Symfony problem with range Datetime (form)

Tags: , ,



I don’t understand my problem. If you can just give me an idea. I have a dateTime field who works but my field years have a bizzare range (2015-2025). I want to have a bigger range (e.g : 1960-2040).

class BookType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('author')
            ->add('publicationDate')
            ->add('format')
            ->add('language')
            ->add('user')
            ->add('excelFile', FileType::class,[
                'label' => 'Fichier excel (xls/xlsx file)',
                'mapped' => false,
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid xls/xlsx document',
                    ])
                ]
            ])
        ;
    }

Answer

As you can see here DateType::Class Refrence. The field will have options to configure how your choice box will behave. you can simply use php’s range() function to map out your Years in your code like : range(1960, 2040)

$builder->add('field', DateType::Class , [
    'years' => range(date('Y')-50, date('Y')+50) // Lists 50 Years Before and After
]);

In your code simply use :

class BookType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('author')
            ->add('publicationDate', DateType::Class , [
                'years' => range(1960, date('Y')+20) // Change As eper your requirements
            ])
            ->add('format')
            ->add('language')
            ->add('user')
            ->add('excelFile', FileType::class,[
                'label' => 'Fichier excel (xls/xlsx file)',
                'mapped' => false,
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid xls/xlsx document',
                    ])
                ]
            ])
        ;
    }


Source: stackoverflow