2016-09-08 47 views
1

我有一個奇怪的問題。即使對無效數據,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

+0

是名稱設置爲不可空的實體? – olibiaz

+0

請使用'handleRequest'來代替'submit'和'isSumitted'來代替'isMethod'來查看示例最佳實踐http://symfony.com/doc/current/best_practices/forms.html#handling-form-submits並稍後檢查您的「聯繫人」類中的約束。 – yceruto

+0

是的,它被設置爲非空(或未引用變量的默認原則行爲)。但我一直認爲我的表單字段的定義是如果它是或不需要的。 我試過handleRequest和isSubmitted,但這只是不同的方法如何從submited形式獲取數據。驗證本身並不適用於兩種方式。 –

回答

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

+0

我向實體添加了斷言約束,但它沒有幫助。我會嘗試這個可能的解決方案,然後可能會開始深入symfony,爲什麼驗證不起作用。 –

0

可能,確認是不是 「名稱」 字段啓用。 要啓用它 - 添加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(), 
      ], 
     ]) 
相關問題