我对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文档和类似的问题,但似乎都不太适合我的情况。我不知道。
setDefaultOptions
已经被弃用,推荐使用configureOptions
。更多信息请参考http://symfony.com/blog/new-in-symfony-2-7-form-and-validator-updates#deprecated-setdefaultoptions-in-favor-of-configureoptions。 - DarksteelPenguin