Symfony表单即使对无效数据也有效

时间:2016-09-08 21:07:27

标签: php forms validation symfony

我有一个奇怪的问题。

即使提供的数据不是,我的表单也会被symfony有效。此表单由ajax请求创建和发布(这可能会影响它)

    if(!$request->isXmlHttpRequest()){
        return new JsonResponse(['code' => 403], 403);
    }

    $name = $request->query->get('name');

    $contact = new Contact();
    $contact->setName($name);

    $form = $this->get('form.factory')->create(ContactType::class, $contact);

    if($request->isMethod('POST')){
        $form->submit($request);
        if($form->isValid()){
            $em = $this->get('doctrine.orm.entity_manager');

            $em->persist($contact);
            $em->flush();

            return new JsonResponse(['code' => 200, 'id' => $contact->getId(), 'name' => $contact->getName()]);
        }

        return new JsonResponse(['formView' => $this->renderView('@MyBundle/Contacts/contactForm.html.twig',['form' =>$form->createView()]), 'code' => 400, 'errors' => $form->getErrors(true)]);
    }

    return new JsonResponse(['formView' => $this->renderView('@MyBundle/Contacts/contactForm.html.twig',['form' =>$form->createView()]), 'code' => 200], 200);

数据看起来像这样(用xdebug引用):

   'id' => NULL,
   'name' => NULL,
   'companyId' => NULL,
   'companyTaxId' => NULL,
   'birthNumber' => NULL,
   'phoneLandLine' => NULL,
   'phoneMobile' => NULL,
   'phoneFax' => NULL,
   'email' => NULL,
   'www' => NULL,

问题是,即使表单被标记为有效且没有错误,该名称(根据需要设置)也为null。在此之后,有一个关于缺少必填字段的学说例外。

你知道为什么会发生这种情况吗?

Symfony v2.8.10,Doctrine v1.6.4

2 个答案:

答案 0 :(得分:1)

可能未对“名称”字段启用验证。 要启用它 - 将NotBlank注释添加到您的实体:

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 *     
 * @Assert\NotBlank()
 */
private $name;

http://symfony.com/doc/current/reference/constraints/NotBlank.html

或直接向表单添加约束:

$builder
        ->add('name', TextType::class, [
            'constraints' => [
                new \Symfony\Component\Validator\Constraints\NotBlank(),
            ],
        ])

答案 1 :(得分:0)

必需属性不作为验证程序。 引自http://symfony.com/doc/2.8/reference/forms/types/text.html#required

  

如果为true,则将呈现HTML5必需属性。相应的标签也将使用必需的类进行渲染。

     

这是肤浅的,独立于验证。充其量,如果您让Symfony猜测您的字段类型,那么将从您的验证信息中猜出此选项的值。

查看http://symfony.com/doc/2.8/forms.html#form-validation

相关问题