2015-10-16 72 views
2

如何將驗證器添加到自定義表單類型? IBAN爲例。將驗證器添加到自定義表單類型

use Symfony\Component\Validator\Constraints\IbanValidator; 

class IBANType extends AbstractType 
{ 
    public function getName() 
    { 
     return 'iban'; 
    } 

    public function getParent() 
    { 
     return 'text'; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     //IbanValidator ??? 
    } 
} 

Here他們建議使用監聽器:

The interface FormValidatorInterface was deprecated and will be removed in Symfony 2.3.

If you implemented custom validators using this interface, you can substitute them by event listeners listening to the FormEvents::POST_BIND (or any other of the *BIND events). In case you used the CallbackValidator class, you should now pass the callback directly to addEventListener.

怎麼會呢?

回答

3

試試這個:

use Symfony\Component\Validator\Constraints\IbanValidator; 

class IBANType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->add('iban', 'text', [ 
      'constraints' => [ 
       new IbanValidator(), 
      ], 
     ]); 
    } 
} 
+0

有關它的更多信息也查看文檔:http://symfony.com/doc/current/book/forms.html#adding-validation – jahller

+1

爲什麼我需要添加新字段?我明顯的錯誤:「你不能添加孩子到一個簡單的形式。也許你應該設置選項」複合「爲真? – VladRia

+1

這只是一個如何在FromBuilder中驗證威脅的例子...... – scoolnico

相關問題