我有一個奇怪的問題。即使對無效數據,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的retvrieved):
'id' => NULL,
'name' => NULL,
'companyId' => NULL,
'companyTaxId' => NULL,
'birthNumber' => NULL,
'phoneLandLine' => NULL,
'phoneMobile' => NULL,
'phoneFax' => NULL,
'email' => NULL,
'www' => NULL,
的問題是,這個名字,它被設置根據需要,它是空的,即使表單被標記爲有效並且沒有錯誤。在此之後,有一個關於缺少必填字段的原則例外。
你有什麼線索爲什麼會發生這種情況?
Symfony的v2.8.10,學說v1.6.4
是名稱設置爲不可空的實體? – olibiaz
請使用'handleRequest'來代替'submit'和'isSumitted'來代替'isMethod'來查看示例最佳實踐http://symfony.com/doc/current/best_practices/forms.html#handling-form-submits並稍後檢查您的「聯繫人」類中的約束。 – yceruto
是的,它被設置爲非空(或未引用變量的默認原則行爲)。但我一直認爲我的表單字段的定義是如果它是或不需要的。 我試過handleRequest和isSubmitted,但這只是不同的方法如何從submited形式獲取數據。驗證本身並不適用於兩種方式。 –