2012-01-02 14 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の制約を追加することができますか?

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エラーを取得する:私はvalidation.ymlにこれを追加しようとしました。

私はreCAPTCHAのフィールドのオプションから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

+2

symfony 2.1では、 'property_path = false'の代わりに' mapped = false'を使うべきです。http://symfony.com/doc/current/reference/forms/types/form.html#property-pathとhttp: //symfony.com/doc/current/reference/forms/types/form.html#mappedとなります。 –

関連する問題