php Symfony2 - 使用不附加任何实体的表单生成器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16883117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symfony2 - Using Form Builder Without Any Entity Attached
提问by Josh Wa
I have been using the form builder with Symfony2, and find it quite nice. I find myself wanting to create a search page with a series of boxes at the top to filter search results. I have three different entities as of now (judges, interpreters, attorneys). I would like the users to be able to enter partial or complete names, and have it search all of the entities. I can handle the actual searching part, but the form builder generation is what is giving me trouble.
我一直在使用 Symfony2 的表单构建器,发现它非常好。我发现自己想要创建一个顶部有一系列框的搜索页面来过滤搜索结果。到目前为止,我有三个不同的实体(法官、口译员、律师)。我希望用户能够输入部分或完整名称,并让它搜索所有实体。我可以处理实际的搜索部分,但表单生成器的生成给我带来了麻烦。
What I am trying to do is create a form not attached to any particular entity. All the tutorials and documentation I've read on the Symfony site acts like it should be attached to an entity by default. I am wondering if I should just attach it to any entity and just set each text field to mapped = false, if this is an instance where I should just hard code the form myself, or if there is some way to do this within form builder.
我想要做的是创建一个不附加到任何特定实体的表单。我在 Symfony 站点上读过的所有教程和文档都表现得好像默认情况下应该附加到实体一样。我想知道我是否应该将它附加到任何实体并将每个文本字段设置为映射 = false,如果这是一个我应该自己硬编码表单的实例,或者是否有某种方法可以在表单生成器中执行此操作.
回答by lifo
Don't use a formType and you don't need to attach an entity in order to use the Form Builder. Simply use an array instead. You probably overlooked this small section in the Symfony documentation: http://symfony.com/doc/current/form/without_class.html
不要使用 formType 并且您不需要附加实体来使用表单构建器。只需使用数组即可。您可能忽略了 Symfony 文档中的这一小部分:http: //symfony.com/doc/current/form/without_class.html
<?php
// inside your controller ...
$data = array();
$form = $this->createFormBuilder($data)
->add('query', 'text')
->add('category', 'choice',
array('choices' => array(
'judges' => 'Judges',
'interpreters' => 'Interpreters',
'attorneys' => 'Attorneys',
)))
->getForm();
if ($request->isMethod('POST')) {
$form->handleRequest($request);
// $data is a simply array with your form fields
// like "query" and "category" as defined above.
$data = $form->getData();
}
回答by Farid Movsumov
You can also use createNamedBuilder
method for creating form
您还可以使用createNamedBuilder
创建表单的方法
$form = $this->get('form.factory')->createNamedBuilder('form', 'form')
->setMethod('POST')
->setAction($this->generateUrl('upload'))
->add('attachment', 'file')
->add('save', 'submit', ['label' => 'Upload'])
->getForm();