Php Symfony2:将选项传递给buildForm
所以我对Symfony很陌生,我正试图让控制器基于控制器动作构建稍微不同的表单。现在,我有这个Php Symfony2:将选项传递给buildForm,php,symfony,Php,Symfony,所以我对Symfony很陌生,我正试图让控制器基于控制器动作构建稍微不同的表单。现在,我有这个 //in Controller public function addLocationEntryAction(Request $request) { $entry = new Entry(); $form = $this->get('form.factory')->create(new EntryType('addLocation'), $entry); ret
//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()
));
}
及
我想在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文档和类似的问题,但似乎没有什么东西适合我的情况。我不知道。无需创建其他参数,只需使用
选项
传递自定义数据即可。在下面的示例中,我将age
属性设置为必填,您可以将其设置为可选或指定默认值。阅读有关选项分解器的更多信息
创建:
$form = $this->get('form.factory')->create(new ExampleType(), $entry, array(
'age' => 13
));
@b、 b3rn4rd是最好的答案!清晰、简单、有效。在我的例子中,它也可以正常工作请注意,
setDefaultOptions
被弃用,取而代之的是configureOptions
。
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
));