2014-06-23 43 views
0

我有類似的問題,以這樣的: Replace an object with Null value Using Form Builder in Symfony2替換對象爲空形式的Symfony2

我有具有多對一關係到另一個實體,稱爲TypeClassification(一個分類屬於一種類型的分類,或實體稱爲分類沒有類型化)。

Classification.php:

/** 
* @ORM\ManyToOne(targetEntity="TypeClassification", inversedBy="classifications", fetch="EAGER") 
*/ 
private $typeclassification; 

TypeClassification.php:

/** 
* @ORM\OneToMany(targetEntity="Classification", mappedBy="typeclassification") 
*/ 
private $classifications; 

的形式通過symfony的作品默認生成的分類,這裏是代碼:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('name') 
     ->add('namejapanese') 
     ->add('ldapid') 
     ->add('typeclassification','entity', array('class' => 'ACMEMyBundle:TypeClassification','required' => false)); 
} 

我問題依賴於實體選擇領域。我想允許Null值,並將關係設置爲Null。

正如我所說的它的工作原理,到目前爲止,但只要我添加驗證約束的實體分類,即使他們沒有涉及到的關係都:

validation.yml:

ACME\MyBundle\Entity\Classification: 
#If I commend this constraints, everything works properly. 
constraints:  
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields: name, message: unique.name } 
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: { fields: ldapid, message: unique.ldapid } 
#For this properties doesn't matter if they are here or not 
properties: 
    name: 
     - NotBlank: 
      message: not.blank 
    namejapanese: 
     - NotBlank: 
      message: not.blank 
    ldapid: 
     - NotBlank: 
      message: not.blank 

然後我無法將關係設置爲Null。但是如果我評論約束部分,那麼我可以將其設置爲Null。

爲什麼會發生這種情況?我怎樣才能讓它具有這種驗證和將關係設置爲空的能力?

回答

1

這是因爲UniqueEntity約束驗證程序,它將null視爲重複項。創建您自己的validator服務並在那裏進行檢查。

+0

謝謝,很高興知道爲什麼,我想我應該閱讀更多文檔。 (我很懶,但創建了驗證器(:) – Cesc