symfony - 如何在symfony2中选择年份

标签 symfony

我想选择显示从 1960 年到当前年份的年份,因此在提交后我应该有一个类似 :1989 的字符串。

我尝试了这样的方法,但不起作用:

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

最佳答案

这非常简单。
如果提交表单后您想要一个年份字符串,只需生成一个自 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);
    }
}

模板:

enter image description here

表单提交后:

enter image description here

关于symfony - 如何在symfony2中选择年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34812735/

相关文章:

php - Composer - phpseclib 需要打开失败

php - 运行时通知 : Declaration of in symfony2

symfony - Doctrine 迁移在项目中间开始

Symfony 2.1 Doctrine 过滤器(启用/禁用)

symfony - 学说 targetEntity 抽象类

php - 如何在 onFlush 事件监听器中更新实体的 manyToMany 集合?

symfony - Google App Engine 上的 document_root 无法识别

php - 在 Symfony PHP 中重定向来自事件订阅者的响应

mongodb - 无法使用 DoctrineMongoDBBundle 检索 @Collection 类型字段的值

git - 如何克隆特定版本的 git 存储库?