Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在symfony2中选择年份_Symfony - Fatal编程技术网

如何在symfony2中选择年份

如何在symfony2中选择年份,symfony,Symfony,我想做一个选择,显示从1960年到今年的年份,所以在我提交它之后,我应该有一个字符串,比如:1989年 我试过这样做,但不起作用: ->add('years', 'date', array( 'widget' => 'choice', 'format' => 'yyyy-MM-dd', 'years' => range(date('Y'), date('Y') -

我想做一个选择,显示从1960年到今年的年份,所以在我提交它之后,我应该有一个字符串,比如:1989年

我试过这样做,但不起作用:

 ->add('years', 'date', array(
                'widget' => 'choice',
                'format' => 'yyyy-MM-dd',
                'years'       => range(date('Y'), date('Y') - 30, -1)))

将DateInterval类PHP用于此模式:

$interval = new DateInterval('P30Y');
有了你的参考日期,开始就很容易了。 如果提交表单后需要年份字符串,只需生成自1960年以来的年份数组,如下所示:

class MyClassType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('year',
                'Symfony\Component\Form\Extension\Core\Type\ChoiceType',[
                'choices' => $this->getYears(1960)
            ])
            # or (for symfony <= 2.7):
            # ->add('year', 'choice', ['choices' => $this->getYears(1960)])

        ;
    }

    private function getYears($min, $max='current')
    {
         $years = range($min, ($max === 'current' ? date('Y') : $max));

         return array_combine($years, $years);
    }
}
模板:

提交表格后:


日期类型将返回\DateTime实例。如果您只想检索年份,那么应该查看选项类型。我尝试了以下方法:->添加'years','choice',数组'widget'=>'choice','format'=>'yyyy-MM-dd','years'=>rangedate'Y',date'Y'-30,-1但它不起作用。您应该查看coice类型的可用选项。选项类型既没有格式、小部件,也没有年份选项。如果你只想拥有年份,那么像yyy-MM-dd这样的格式毫无意义。你能帮我写代码吗?我是symfony的初学者,谢谢