日期时间范围(表单)的 Symfony 问题

Symfony problem with range Datetime (form)

我不明白我的问题。 如果你能给我一个想法。 我有一个有效的 dateTime 字段,但是 我的领域年份有一个奇怪的范围(2015-2025)。 我想要更大的范围(例如: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',
                    ])
                ]
            ])
        ;
    }

如您所见DateType::Class Refrence。该字段将有选项来配置您的选择框的行为方式。您可以简单地使用 php 的 range() 函数在您的代码中映射您的年份,例如:range(1960, 2040)

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

在您的代码中只需使用:

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',
                    ])
                ]
            ])
        ;
    }