如何在FormType上循环Symfony2中的值

时间:2015-05-18 18:49:12

标签: php symfony

我有这段代码:

->add('breedingPairSeason', 'choice', array(
    'placeholder' => 'Choose a season',
    'choices' => array(
        'early2010'   => 'Early 2010 (Jan - June)',
        'late2010' => 'Late 2010 (July - December)',
    ),
));

我想要实现的是根据年份自动添加更多选择。理想情况下,我希望它从2010年开始,然后在今年完成,如下:

->add('breedingPairSeason', 'choice', array(
    'placeholder' => 'Choose a season',
    'choices' => array(
        'early2010'   => 'Early 2010 (Jan - June)',
        'late2010' => 'Late 2010 (July - December)',
        'early2011'   => 'Early 2011 (Jan - June)',
        'late2011' => 'Late 2011 (July - December)',
        'early2012'   => 'Early 2012 (Jan - June)',
        'late2012' => 'Late 2012 (July - December)',
        'early2013'   => 'Early 2013 (Jan - June)',
        'late2013' => 'Late 2013 (July - December)',
        'early2014'   => 'Early 2014 (Jan - June)',
        'late2014' => 'Late 2014 (July - December)',
        'early2015'   => 'Early 2015 (Jan - June)',
        'late2015' => 'Late 2015 (July - December)',
    ),
));

这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以为枚举创建简单文件,也可以在表单中使用私有方法来实现此目的。我将向您展示一个快速示例,但总的来说,如果您找到更好/更清洁的方式,生成阵列取决于您。

假设您在表单类型中创建了一个私有方法:

private function _getSeasonChoices() {
    $intervalStart = 2010;
    $intervalEnd = (new \DateTime('now'))->format('Y');

    $choices = array();
    for($year = $intervalStart; $year <= $intervalEnd; $year++) {

        $choices[ sprintf('early%d', $year) ] = sprintf('Early %d (January - June)', $year);
        $choices[ sprintf('late%d', $year) ] = sprintf('Late %d (July - December)', $year);

    }

    return $choices;
}

然后你所要做的就是调用方法

'choices' => $this->_getSeasonChoices()

并且您的选择输入应填充正确的值。

同样,如果您对此解决方案不满意,生成阵列完全取决于您。希望你明白了。

答案 1 :(得分:1)

我会做这样的事情:

# namespace SomeBundle\Form\Type
/**
 * Generate a choice array from start year to end year
 *
 * @param int $startYear The start year
 * @param int $endYear If null, current year is taken
 * @return array
 */
protected function generateChoices($startYear, $endYear=null)
{
    $endYear = $endYear ? $endYear : date('Y');
    $years   = range($startYear, $endYear);
    $choices = array();

    foreach($years as $year) {
        $choices['early' . $year] = sprintf('Early %d (Jan - June)', $year);
        $choices['late'  . $year] = sprintf('Late %d (July - December)', $year);
    }

    return $choices;
}

关于建设者:

//...
->add('breedingPairSeason', 'choice', array(
    'placeholder' => 'Choose a season',
    'choices' => $this->generateChoices(2010)
));