【发布时间】:2016-09-08 21:07:27
【问题描述】:
我有一个奇怪的问题。
即使提供的数据不是,我的表单对 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,
问题是,根据需要设置的名称为空,即使表单被标记为有效并且没有错误。在此之后,有一个关于缺少必填字段的原则例外。
你知道为什么会发生这种情况吗?
Symfony v2.8.10,Doctrine v1.6.4
【问题讨论】:
-
实体中的名称是否设置为不可为空?
-
请使用
handleRequest代替submit和isSumitted而不是isMethod在此处查看最佳实践示例symfony.com/doc/current/best_practices/… 并稍后检查Contact类中的约束。 -
是的,它设置为非空(或非引用变量的默认教义行为)。但我一直认为我对表单字段的定义就是说明是否需要。我已经尝试过 handleRequest 和 isSubmitted,但这只是如何从提交的表单中获取数据的不同方法。验证本身并不适用于这两种方式。
标签: php forms validation symfony