2016-03-08 91 views
1

我想在我的表單類型使用自定義的驗證工作,但我得到這個錯誤:symfony的表單類型使用自定義約束/驗證

沒有默認選項配置爲約束的appbundle \驗證\約束\ DnsContent

我有此約束+驗證:

// My constraint 
/** 
* @Annotation 
*/ 
class DnsContent extends Constraint 
{ 
    public $message = 'fail'; 

    /** 
    * {@inheritdoc} 
    */ 
    public function validatedBy() 
    { 
     return 'dns_content'; 
    } 
} 

// My validator 
class DnsContentValidator extends ConstraintValidator 
{ 
    public function validate($type, Constraint $constraint) 
    { 
     switch ($type) { 
      case 'A': 
       return new Assert\Ip(['version' => '4']); 
       break; 
      case 'AAAA': 
       return new Assert\Ip(['version' => '6']); 
       break; 
      case 'CNAME': 
      case 'NS': 
      case 'MX': 
       return new Assert\Regex(['pattern' => '/^[[:alnum:]-\._]+$/u']); 
       break; 
      default: 
       return false; 
       break; 
     } 
    } 
} 

我試圖用它在我的表單類型裏這樣

$contentConstraints = function (FormInterface $form, $type) { 
    $form->add('content', null, [ 
     'label'     => 'form.content', 
     'translation_domain' => 'global', 
     'constraints'   => new DnsContent($type), 
    ]); 
}; 

但是我得到了上面寫的錯誤。 我不明白如何解決這個問題,如果我使用正確的方式在表單類型中使用自定義約束驗證器。

感謝您的幫助

回答

3

嘗試

$form->add('content', null, [ 
     'label'     => 'form.content', 
     'translation_domain' => 'global', 
     'constraints'   => new DnsContent(), 
    ]); 

拋出ConstraintDefinitionException如果不通過一個 關聯數組,但getDefaultOption()返回null

您可以添加自定義選項作爲約束字段

class DnsContent extends Constraint 

    { 
     public $message = 'fail'; 

     public $type; 

     /** 
     * {@inheritdoc} 
     */ 
     public function validatedBy() 
     { 
      return 'dns_content'; 
     } 
    } 

現在你可以通過在陣列

new DnsContent(['type' => $type]) 
+0

這個選項我沒有錯誤了,但我的驗證不使用 –

+0

valdate方法不叫? –

+0

哼哼是的,但我需要通過'type'來使用我的開關盒 –