2013-06-21 132 views
1

如何驗證在我的實體中不存在並且甚至與它們沒有關係的其他表單字段?Symfony2 - 驗證其他表單元素

例如:用戶需要接受的規則,所以我可以添加與映射設置附加複選框假,但我怎麼都不能添加驗證了該領域的約束?

甚至更​​先進的:用戶需要正確地重複他的電子郵件和密碼的形式。我如何驗證它們是一樣的?

我想避免在我的實體添加這些字段,因爲它沒有任何關係。

我使用Symfony 2.3。

回答

2

一種方法是將約束直接掛在表單元素上。例如:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $notBlank = new NotBlank(); 

    $builder->add('personFirstName', 'text', array('label' => 'AYSO First Name', 'constraints' => $notBlank)); 
    $builder->add('personLastName', 'text', array('label' => 'AYSO Last Name', 'constraints' => $notBlank)); 

對於重複的東西,看看重複的元素:http://symfony.com/doc/current/reference/forms/types/repeated.html

審定的另一種方法是創建一個包裝對象對你的實體。包裝器對象將包含其他不相關的屬性。然後你可以在validation.yml中設置你的約束,而不是直接在表單上。

最後,你可以建立一個表單類型只爲一個屬性並添加約束它:

class EmailFormType extends AbstractType 
{ 
public function getParent() { return 'text'; } 
public function getName() { return 'cerad_person_email'; } 

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(array(
     'label'   => 'Email', 
     'attr'   => array('size' => 30), 
     'required'  => true, 
     'constraints'  => array(
      new Email(array('message' => 'Invalid Email')), 
     ) 
    )); 
} 
}