2012-01-02 101 views
6

我試圖將EWZRecaptcha添加到我的註冊表單中。 我的註冊表單生成器看起來是這樣的:Symfony2將reCaptcha字段添加到註冊表格中

public function buildForm(FormBuilder $builder, array $options) 
{ 
    $builder->add('username', 'text') 
      ->add('password') 
      ->add('recaptcha', 'ewz_recaptcha', array('property_path' => false)); 
} 

public function getDefaultOptions(array $options) 
{ 
    return array(
      'data_class' => 'Acme\MyBundle\Entity\User', 
    ); 
} 

現在,我怎麼能添加的ReCaptcha約束來驗證碼字段?我試圖將它添加到validation.yml:

namespaces: 
    RecaptchaBundle: EWZ\Bundle\RecaptchaBundle\Validator\Constraints\ 

Acme\MyBundle\Entity\User: 
    ... 
    recaptcha: 
    - "RecaptchaBundle:True": ~ 

,但我得到Property recaptcha does not exists in class Acme\MyBundle\Entity\User錯誤。

如果我從驗證碼字段的選項中刪除array('property_path' => false),我得到的錯誤:

Neither property "recaptcha" nor method "getRecaptcha()" nor method "isRecaptcha()" 
exists in class "Acme\MyBundle\Entity\User" 

任何想法如何解決呢? :)

回答

4

Acme\MyBundle\Entity\User沒有recaptcha屬性,所以您在嘗試驗證User實體上的該屬性時收到錯誤。設置'property_path' => false是正確的,因爲這告訴Form對象,它不應該嘗試爲域對象獲取/設置此屬性。

那麼如何驗證此表單上的字段並仍然保留User實體?簡單 - 甚至可以在中解釋。您需要自己設置約束並將其傳遞給FormBuilder。下面是你應該結束了一下:

<?php 

use Symfony\Component\Validator\Constraints\Collection; 
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\True as Recaptcha; 

... 

    public function getDefaultOptions(array $options) 
    { 
     $collectionConstraint = new Collection(array(
      'recaptcha' => new Recaptcha(), 
     )); 

     return array(
      'data_class' => 'Acme\MyBundle\Entity\User', 
      'validation_constraint' => $collectionConstraint, 
     ); 
    } 

的一兩件事,我不知道這個方法,無論是這個約束集合將與您validation.yml合併或者它是否會覆蓋它。

您應該閱讀this article,它更深入地解釋瞭如何通過對實體和其他屬性進行驗證來設置表單的正確過程。它特定於MongoDB,但適用於任何Doctrine實體。繼本文之後,請將您的termsAccepted字段替換爲您的recaptcha字段。

+0

偉大的文章,謝謝! – tamir 2012-02-08 17:28:39

+2

由於Symfony 2.1應該使用'mapped = false'而不是'property_path = false',請參閱http://symfony.com/doc/current/reference/forms/types/form.html#property-path和http: //symfony.com/doc/current/reference/forms/types/form.html#mapped。 – 2015-07-11 12:07:05

相關問題