2013-02-12 129 views
3

如何驗證Symfony 2.0中的表單的嵌入式集合(沒有實體)?如果解決方案沿着這條線展開,升級到2.1並不是一個方便的選擇。Symfony 2.0:如何驗證沒有實體的表單的嵌入式集合

我試過使用Valid約束,它導致所有的驗證失敗,而不是。

public function getDefaultOptions(array $options) 
{ 
    $collectionConstraint = new Collection(array (
     ... 

     // I tried Valid constraint but this "removes" all validation 
     'travel_links' => new Valid(), 
    )); 

    return array ('validation_constraint' => $collectionConstraint); 
} 
+0

這樣的事情應該這樣做:http://symfony.com/doc/2.0/book/forms.html#adding-validation – cheesemacfly 2013-02-12 02:26:57

+0

嗨@cheesemacfly,我更新了問題,我的意思是一個*表單集合*。我相信你給的鏈接是用於簡單字段而不是嵌入表單的。 – 2013-02-12 02:37:01

+0

你是對的!我可能太快地讀你的問題了...... – cheesemacfly 2013-02-12 02:40:29

回答

3

在Symfony的2.1,你可以使用約束選項:

$builder 
->add('firstName', 'text', array(
    'constraints' => new Length(array('min' => 3)), 
)) 
->add('lastName', 'text', array(
    'constraints' => array(
     new NotBlank(), 
     new Length(array('min' => 3)), 
), 
)); 

顯然,這不會在Symfony的2.0工作;然而,在Symfony 2.0中提供了一個名爲validation_constraint的有限約束選項。

$builder 
->add('firstName', 'text', array(
    'validation_constraint' => new Length(array('min' => 3)), 
)); 

如果您需要驗證多個條件(例如NotBlank,Lenght),你可以幫助自己,定義Custom constraint做所有驗證一次。 :)

編輯:不要忘記包括use Symfony\Component\Validator\Constraints\Length或任何你使用的約束。 :)

1

在Symfony2.x的實際版本,你可以設置cascade_validation爲true(默認爲false) http://symfony.com/doc/current/reference/forms/types/form.html

的文件說:「此選項設置爲true以強制嵌入形式驗證類型爲。例如,如果您的ProductType具有嵌入的CategoryType,則在ProductType上將cascade_validation設置爲true將導致來自CategoryType的數據也會被驗證。

而不是使用此選項,還可以在模型中使用有效約束強制對存儲在屬性上的子對象進行驗證。「