2015-06-19 20 views
0

我使用表單生成無類,有兩個領域的每一個具有約束:的Symfony2表單生成無類檢查,如果多個字段爲空

$form = $this->createFormBuilder() 
     ->add('name', 'text', array(
      'required'=>false, 
      'constraints'=> new Length(array('min'=>3) 
     )) 
     ->add('dob', 'date', array(
      'required'=>false, 
      'constraints'=> new Date() 
     )) 
     ->getForm() 
     ->handleRequest($request); 

這個偉大的工程,但我要檢查,如果這兩個領域都emtpy ,並顯示錯誤。只是似乎無法得到這個處理。有人可以提供幫助嗎?

+0

做'required'=> true在這兩個表單字段中。 –

回答

2

最簡單的方法是隻設置兩個嘀......

但..上後,你可以檢查一樣簡單

if(empty($form->get('name')->getData()) && empty($form->get('dob')->getData())){ 
    $form->addError(new FormError("fill out both yo")); 
    // ... return your view 
}else { 

    // ... do your persisting stuff 
} 
... 

symfony的方式將有可能增加一個自定義的驗證 我建議你看看custom validator尤其是這part

僞:

namespace My\Bundle\Validator\Constraints; 

use Symfony\Component\Validator\Constraint; 
use Symfony\Component\Validator\ConstraintValidator; 

class CheckBothValidator extends ConstraintValidator 
{ 
    public function validate($foo, Constraint $constraint) 
    { 
      if (!($foo->getName() && $foo->getDob()) { 
       $this->context->addViolationAt('both', $constraint->message, array(), null); 
      } 
    } 
} 
+0

實際上'required'=> false是我想要的。只需要趕上,如果兩個領域都是空的。謝謝。有用。我想知道,如果我可以使用驗證組或回調來處理這個問題?只是試圖學習更多... – WJR

+0

我更新了答案 –

2

裏面你Bundle->Resources->Config文件夾中創建一個文件名validation.yml 然後

namespace\YourBundle\Entity\EntityName: 
    properties: 
     dob://field that you want to put validation on 
      - NotBlank: { message: "Message that you want to display"} 
     gender: 
      - NotBlank: { message: "Message that you want to display" } 

驗證將盡快發揮作用,如您檢查是否提交表單數據的isValid()

$entity = new Programs(); 
     $form = $this->createCreateForm($entity); 
     $form->handleRequest($request); 

     if ($form->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 
      $em->persist($entity); 
      $em->flush(); 
      $this->get('session')->getFlashBag()->add(
       'notice', 
       'Success' 
      ); 
      // your return here 
      return ...; 

     } 
+0

謝謝。我沒有在這方面使用實體。我確實想讓一個領域的空白,但不是兩個空白。我想知道如果我可以添加到createFromBuilder構造,將檢查是否都是空白。 – WJR

相關問題