12
所以我對Symfony很陌生,我試圖讓控制器根據控制器動作構建略微不同的窗體。現在,我有這個Symfony2:將選項傳遞給buildForm
//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文檔和類似的問題,但似乎沒有什麼適合我的情況。我不知道。
工作很漂亮,謝謝你 – Afunakwa
@ b.b3rn4rd最好的答案!清晰,簡單,有效。在我的情況下,它也能很好地工作 –
請注意'setDefaultOptions'已被棄用,以''configureOptions'爲優先。 http://symfony.com/blog/new-in-symfony-2-7-form-and-validator-updates#deprecated-setdefaultoptions-in-favor-of-configureoptions – DarksteelPenguin