gpt4 book ai didi

php - Symfony2 : Passing options to buildForm

转载 作者:行者123 更新时间:2023-12-03 00:01:43 25 4
gpt4 key购买 nike

所以我对 Symfony 还很陌生,我试图让 Controller 根据 Controller 操作构建稍微不同的形式。现在,我有这个

//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 中的 Controller 传递一个选项,以便我可以执行以下操作:

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 文档和类似的问题,但似乎没有什么适合我的情况。我不知道。

最佳答案

无需创建额外的参数,只需使用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
));

关于php - Symfony2 : Passing options to buildForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com