在Symfony2表单中使用选项的函数返回值选项

时间:2015-02-06 15:03:59

标签: php symfony symfony-forms

我有这个Symfony2表格:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
            'nombre',
            'text',
            array(
                'required' => true,
                'mapped'   => false,
                'label'    => 'Nombre'
            )
        )
        ->add(
            'anno_modelo',
            'choice',
            array(
                'placeholder'   => 'Escoja una opción',
                'choices'       => array(),
                'required'      => true
            )
        )
        ->add(
            'anno_fabricacion',
            'choice',
            array(
                'placeholder'   => 'Escoja una opción',
                'choices'       => array(),
                'required'      => true
            )
        );
}

我有这段代码:

function getChoices() {
    $choices = [];
    for($i = date("Y"); $ >= 1900; $i--) {
        $choices[$i - 1] = $i - 1;
    }

    return $choices;
}

我需要将$choices用作choices值,我该如何实现?

1 个答案:

答案 0 :(得分:1)

试试这段代码:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $choices = $this->getChoices();
    $builder
        ->add(
            'nombre',
            'text',
            array(
                'required' => true,
                'mapped'   => false,
                'label'    => 'Nombre'
            )
        )
        ->add(
            'anno_modelo',
            'choice',
            array(
                'placeholder'   => 'Escoja una opción',
                'choices'       => $choices,
                'required'      => true
            )
        )
        ->add(
            'anno_fabricacion',
            'choice',
            array(
                'placeholder'   => 'Escoja una opción',
                'choices'       => $choices,
                'required'      => true
            )
        );
}

private function getChoices() 
{
    $choices = [];
    for($i = date('Y'); $i >= 1900; $i--) {
        $choices[$i - 1] = $i - 1;
    }

    return $choices;
}