Symfony2:将选项传递给buildForm

时间:2015-04-23 01:11:30

标签: php symfony

所以我对Symfony很陌生,我试图让控制器根据控制器动作构建略有不同的形式。现在,我有这个

//in Controller

public function addLocationEntryAction(Request $request)
{
    $entry = new Entry();
    $form = $this->get('form.factory')->create(new EntryType('addLocation'), $entry);

    return $this->render('OOTNBlogBundle:Blog:addEntry.html.twig', array(
        'form' => $form->createView()
    ));
}

public function addArticleEntryAction(Request $request)
{
    $entry = new Entry();
    $form = $this->get('form.factory')->create(new EntryType('addArticle'), $entry);

    return $this->render('OOTNBlogBundle:Blog:addEntry.html.twig', array(
        'form' => $form->createView()
    ));
}

并且

//in EntryType

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('title',      'text')
        ->add('continent',  'text', array('required' => false))
        ->add('country',    'text', array('required' => false))
        ->add('category',   'text', array('required' => false))
        ->add('author',     'hidden')
        ->add('type',       'hidden')
        ->add('text',       'textarea')
        ->add('post',       'submit')
    ;
}

我想从buildForm中的控制器传递一个选项,以便我可以这样做:

public function buildForm(FormBuilderInterface $builder, array $options, $option)
{
    $builder
        ->add('title',      'text')
    ;

    if($option == 'addLocation')
    {
        $builder
            ->add('continent',  'text', array('required' => false))
            ->add('country',    'text', array('required' => false))
        ;
    }
    elseif($option == 'addArticle')
    {
        $builder
            ->add('category',   'text', array('required' => false))
        ;
    }

    $builder
        ->add('author',     'hidden')
        ->add('type',       'hidden')
        ->add('text',       'textarea')
        ->add('post',       'submit')
    ;
}

我该怎么做?我已经在这里检查了Symfony doc和类似的问题,但似乎没有什么比我的情况更合适。我不知道。

1 个答案:

答案 0 :(得分:16)

无需创建其他参数,只需使用options传递自定义数据即可。在以下示例中,我将age属性设置为必需,您可以将其设置为可选或指定默认值。详细了解OptionsResolver here

class ExampleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        var_dump($options['age']);
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired(array(
            'age'
        ));

    }
}

创建:

$form = $this->get('form.factory')->create(new ExampleType(), $entry, array(
    'age' => 13
));