php Symfony2.4 表单“此表单不应包含额外字段”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23018907/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:26:05  来源:igfitidea点击:

Symfony2.4 form 'This form should not contain extra fields' error

phpformsangularjssymfonysymfony-2.4

提问by mmmm

I'm trying to build app based on REST api ang AngularJS. I've been following this tutorial http://npmasters.com/2012/11/25/Symfony2-Rest-FOSRestBundle.htmlbut have to change some details ( depreciated methods ) and right now when I post to create new entity I get 'This form should not contain extra fields' error.

我正在尝试基于 REST api 和 AngularJS 构建应用程序。我一直在关注本教程http://npmasters.com/2012/11/25/Symfony2-Rest-FOSRestBundle.html但必须更改一些细节(折旧方法),现在当我发布以创建新实体时,我得到“此表单不应包含额外字段”错误。

class MainController extends Controller
{
    public function indexAction(Request $request)
    {
        $form = $this->createForm(new TaskType(),null,array('action' => $this->generateUrl('post_tasks').'.json'))
                ->add('submit','submit');


        $note_form = $this->createForm(new NoteType())
                ->add('submit','submit');

        return $this->render('MyBundle:Main:index.html.twig',
                array(
                    'form'=>$form->createView(),
                    'note_form'=>$note_form->createView(),
                )
        );
    }
}

my TaskType form:

我的 TaskType 表单:

 public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder

            ->add('timeStart','datetime',array(
                'date_widget' => 'single_text',
                'time_widget' => 'single_text',
                'date_format' => 'yyyy-MM-dd',
                'data' => new \DateTime('now')
            ))

            ->add('timeStop','datetime',array(
                'date_widget' => 'single_text',
                'time_widget' => 'single_text',
                'date_format' => 'yyyy-MM-dd',
                'data' => new \DateTime('now')
            ))

            ->add('project')  
            ->add('descriptionTask')
            ->add('isCompleted',null,array('required' => false))  
            ->add('isVisible',null,array('required' => false))
        ;
    }

right now in my view I'm rendering only one form BUT I'M IN THE TEST STAGE:

现在在我看来,我只渲染一种形式,但正处于测试阶段

{%extends 'MyBundle::layout.html.twig' %}

{%block content %}

<div ng-view></div>

{{ form(form) }}

{% endblock %}

AND this is the REST controller which is supposed to flush given entity:

这是应该刷新给定实体的 REST 控制器:

public function cpostAction(Request $request)
{
 $entity = new Task();
 $form = $this->createForm(new TaskType(), $entity);
 $form->handleRequest($request);

 if ($form->isValid()) {

     $em = $this->getDoctrine()->getManager();
     $em->persist($entity);
     $em->flush();

     return $this->redirectView(
             $this->generateUrl(
                 'get_organisation',
                 array('id' => $entity->getId())
                 ),
             Codes::HTTP_CREATED
             );
 }

 return array(
     'form' => $form,
 );
}

WEIRD THING: when I put the same code from REST controller to MainController, then form is validatedand new entity is being flushed, but somehow REST controller throws error...

奇怪的事情:当我将相同的代码从 REST 控制器放入 MainController 时,表单被验证并刷新新实体,但不知何故 REST 控制器抛出错误......

回答by Rudiger

If you want the validator to ignore additional fields you should try passing 'allow_extra_fields' => trueas an option to the FormBuilder.

如果您希望验证器忽略其他字段,您应该尝试将其'allow_extra_fields' => true作为选项传递给 FormBuilder。

回答by Chase

Its because when you are generating the form you are adding submit buttons but when you are validating them you are not. try:

这是因为当您生成表单时,您正在添加提交按钮,但当您验证它们时却没有。尝试:

public function cpostAction(Request $request)
{
    $entity = new Task();
    $form = $this->createForm(new TaskType(), $entity)->add('submit','submit');
    ...

The submit button is technically a field even though symfony wont map it to an entity property by default. So when you generate the form with a submit button and then submit that form the form you generate in your validation controller action needs to also have a submit button.

尽管默认情况下 symfony 不会将提交按钮映射到实体属性,但提交按钮在技术上是一个字段。因此,当您使用提交按钮生成表单然后提交该表单时,您在验证控制器操作中生成的表单也需要有一个提交按钮。

回答by Dapter20

If you wanna disable fields validation, you must add

如果要禁用字段验证,则必须添加

public function setDefaultOptions(\Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'csrf_protection' => false,
        'validation_groups' => false,
    ));
}

And in buildForm method:

在 buildForm 方法中:

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->addEventListener(FormEvents::POST_SUBMIT, function ($event) {
            $event->stopPropagation();
        }, 900);
        $builder->add('field1','text')
                ->add('field2','text')
                .
                .
                .
    } 

For more details: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-dynamic-form-modification-suppressing-form-validation

更多详情:http: //symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-dynamic-form-modification-suppressing-form-validation

回答by tlarson

If you are adding a single SubmitType button or similar, you use the solution Chausser indicated

如果您要添加单个 SubmitType 按钮或类似按钮,请使用 Chausser 指示的解决方案

$entity = new Task();
$form = $this->createForm(new TaskType(), $entity)->add('submit','SubmitType::class');

However, in case you are using a CollectionType and embedding a set of sub forms, you need to include 'allow_add' => true in your parameters for that type. For example, in your EntityType form builder:

但是,如果您使用 CollectionType 并嵌入一组子表单,则需要在该类型的参数中包含 'allow_add' => true 。例如,在您的 EntityType 表单构建器中:

$builder->add('subEntities', CollectionType::class, array(
                'entry_type' => SubEntityType::class,
                'entry_options' => array('label' => false),
                'allow_add' => true,
            ))

Make sure you do that for all levels of embedding if you have multiple levels.

如果您有多个级别,请确保对所有级别的嵌入都这样做。