symfony2 / symfony3でfosuserbundleを使用して、ユーザー名フィールドを電子メールで削除 /交換します

StackOverflow https://stackoverflow.com/questions/8832916

  •  27-10-2019
  •  | 
  •  

質問

ログインモードとしてのメールだけが必要です。ユーザー名は必要ありません。 Symfony2/Symfony3とFosuserbundleで可能ですか?

ここで読みました http://groups.google.com/group/symfony2/browse_thread/thread/92ac92eb18b423fe

しかし、その後、私は2つの制約違反で立ち往生しています。

問題は、ユーザーがメールアドレスを空白のままにしておくと、2つの制約違反を取得します。

  • ユーザー名を入力してください
  • メールを入力してください

特定のフィールドの検証を無効にする方法、またはフォームからフィールドを完全に削除するより良い方法はありますか?

役に立ちましたか?

解決

何をする必要があるかの完全な概要

これが必要なことの完全な概要です。この投稿の最後にあちこちで見つかったさまざまなソースをリストしました。

1.セッターをオーバーライドします Acme\UserBundle\Entity\User

public function setEmail($email)
{
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername($email);

    return $this;
}

2.フォームタイプからユーザー名フィールドを削除します

(両者に RegistrationFormTypeProfileFormType)

public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);
    $builder->remove('username');  // we use email as the username
    //..
}

3.検証の制約

@nurikabeで示されているように、によって提供された検証の制約を取り除く必要があります FOSUserBundle そして、私たち自身を作ります。これは、以前に作成されたすべての制約を再作成する必要があることを意味します FOSUserBundle そして、関係するものを削除します username 分野。作成する新しい検証グループは AcmeRegistrationAcmeProfile. 。したがって、私たちはによって提供されたものを完全に無効にしています FOSUserBundle.

3.a. configファイルをに更新します Acme\UserBundle\Resources\config\config.yml

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Acme\UserBundle\Entity\User
    registration:
        form:
            type: acme_user_registration
            validation_groups: [AcmeRegistration]
    profile:
        form:
            type: acme_user_profile
            validation_groups: [AcmeProfile]

3.B.検証ファイルを作成します Acme\UserBundle\Resources\config\validation.yml

それは長いビットです:

Acme\UserBundle\Entity\User:
    properties:
    # Your custom fields in your user entity, here is an example with FirstName
        firstName:
            - NotBlank:
                message: acme_user.first_name.blank
                groups: [ "AcmeProfile" ]
            - Length:
                min: 2
                minMessage: acme_user.first_name.short
                max: 255
                maxMessage: acme_user.first_name.long
                groups: [ "AcmeProfile" ]



# Note: We still want to validate the email
# See FOSUserBundle/Resources/config/validation/orm.xml to understand
# the UniqueEntity constraint that was originally applied to both
# username and email fields
#
# As you can see, we are only applying the UniqueEntity constraint to 
# the email field and not the username field.
FOS\UserBundle\Model\User:
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: 
             fields: email
             errorPath: email 
             message: fos_user.email.already_used
             groups: [ "AcmeRegistration", "AcmeProfile" ]

    properties:
        email:
            - NotBlank:
                message: fos_user.email.blank
                groups: [ "AcmeRegistration", "AcmeProfile" ]
            - Length:
                min: 2
                minMessage: fos_user.email.short
                max: 255
                maxMessage: fos_user.email.long
                groups: [ "AcmeRegistration", "ResetPassword" ]
            - Email:
                message: fos_user.email.invalid
                groups: [ "AcmeRegistration", "AcmeProfile" ]
        plainPassword:
            - NotBlank:
                message: fos_user.password.blank
                groups: [ "AcmeRegistration", "ResetPassword", "ChangePassword" ]
            - Length:
                min: 2
                max: 4096
                minMessage: fos_user.password.short
                groups: [ "AcmeRegistration", "AcmeProfile", "ResetPassword", "ChangePassword"]

FOS\UserBundle\Model\Group:
    properties:
        name:
            - NotBlank:
                message: fos_user.group.blank
                groups: [ "AcmeRegistration" ]
            - Length:
                min: 2
                minMessage: fos_user.group.short
                max: 255
                maxMessage: fos_user.group.long
                groups: [ "AcmeRegistration" ]

FOS\UserBundle\Propel\User:
    properties:
        email:
            - NotBlank:
                message: fos_user.email.blank
                groups: [ "AcmeRegistration", "AcmeProfile" ]
            - Length:
                min: 2
                minMessage: fos_user.email.short
                max: 255
                maxMessage: fos_user.email.long
                groups: [ "AcmeRegistration", "ResetPassword" ]
            - Email:
                message: fos_user.email.invalid
                groups: [ "AcmeRegistration", "AcmeProfile" ]

        plainPassword:
            - NotBlank:
                message: fos_user.password.blank
                groups: [ "AcmeRegistration", "ResetPassword", "ChangePassword" ]
            - Length:
                min: 2
                max: 4096
                minMessage: fos_user.password.short
                groups: [ "AcmeRegistration", "AcmeProfile", "ResetPassword", "ChangePassword"]


FOS\UserBundle\Propel\Group:
    properties:
        name:
            - NotBlank:
                message: fos_user.group.blank
                groups: [ "AcmeRegistration" ]
            - Length:
                min: 2
                minMessage: fos_user.group.short
                max: 255
                maxMessage: fos_user.group.long
                groups: [ "AcmeRegistration" ]

4.終了

それでおしまい!あなたは行くのがいいはずです!


この投稿に使用されるドキュメント:

他のヒント

詳細な登録とプロファイルフォームの両方のタイプをオーバーライドすることでこれを行うことができました ここ ユーザー名フィールドを削除します

$builder->remove('username');

コンクリートユーザークラスのセットメールメソッドをオーバーライドするとともに:

 public function setEmail($email) 
 {
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername($email);
  }

マイケルが指摘しているように、これはカスタム検証グループで解決できます。例えば:

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: App\UserBundle\Entity\User
    registration:
        form:
            type: app_user_registration
            validation_groups: [AppRegistration]

次に、エンティティで(によって定義されています user_class: App\UserBundle\Entity\User)Appregistrationグループを使用できます。

class User extends BaseUser {

    /**
     * Override $email so that we can apply custom validation.
     * 
     * @Assert\NotBlank(groups={"AppRegistration"})
     * @Assert\MaxLength(limit="255", message="Please abbreviate.", groups={"AppRegistration"})
     * @Assert\Email(groups={"AppRegistration"})
     */
    protected $email;
    ...

これは、symfony2スレッドへのその返信を投稿した後、私がやったことです。

見る http://symfony.com/doc/2.0/book/validation.html#validation-groups 詳細については。

SF 2.3の時点で、a クイック回避策 ベースザーを拡張するクラスユーザーの_constructで、任意の文字列にユーザー名を設定することです。

public function __construct()
    {
        parent::__construct();
        $this->username = 'username';
    }

このようにして、Validatorは違反をトリガーしません。ただし、投稿者としてユーザー名にメールを設定することを忘れないでください パット.

public function setEmail($email)
{
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername($email);
}

ユーザーへの参照について他のファイルを確認する必要がある場合があります:それに応じてユーザー名と変更します。

検証をカスタマイズしてみましたか?

これを行うには、ユーザーバンドルから独自のバンドルを継承し、リソース/config/validation.xmlをコピー/調整する必要があります。さらに、config.ymlのvalidation_groupsをカスタム検証に設定する必要があります。

検証の置換の代わりに、登録FORMHANDLER#プロセスを置き換えることを好みます。より正確には、元の方法のコピーである新しいメソッドプロセスを追加し、登録コントローラーでUTを使用します。 (オーバーライド: https://github.com/friendsofsymfony/fosuserbundle/blob/master/resources/doc/index.md#next-steps)

登録フォームにバインドする前に、「空」などのユーザー名を設定します。

class RegistrationFormHandler extends BaseHandler
{

    public function processExtended($confirmation = false)
    {
        $user = $this->userManager->createUser();
        $user->setUsername('empty'); //That's it!!
        $this->form->setData($user);

        if ('POST' == $this->request->getMethod()) {


            $this->form->bindRequest($this->request);

            if ($this->form->isValid()) {

                $user->setUsername($user->getEmail()); //set email as username!!!!!
                $this->onSuccess($user, $confirmation);

                /* some my own logic*/

                $this->userManager->updateUser($user);
                return true;
            }
        }

        return false;
    }
    // replace other functions if you want
}

なんで?ユーザーfosuserbundle検証ルールを好みます。 cuz config.ymlの検証グループを登録フォームに置き換える場合、自分のユーザーエンティティでユーザーの検証ルールを繰り返す必要があります。

それらのどれも機能しない場合、迅速で汚い解決策は

public function setEmail($email)
{
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername(uniqid()); // We do not care about the username

    return $this;
}

ユーザー名をNullableにしてから、フォームタイプから削除できます。

初め, 、 の appbundle entity user, 、ユーザークラスの上に注釈を追加します

use Doctrine\ORM\Mapping\AttributeOverrides;
use Doctrine\ORM\Mapping\AttributeOverride;

/**
 * User
 *
 * @ORM\Table(name="fos_user")
 *  @AttributeOverrides({
 *     @AttributeOverride(name="username",
 *         column=@ORM\Column(
 *             name="username",
 *             type="string",
 *             length=255,
 *             unique=false,
 *             nullable=true
 *         )
 *     ),
 *     @AttributeOverride(name="usernameCanonical",
 *         column=@ORM\Column(
 *             name="usernameCanonical",
 *             type="string",
 *             length=255,
 *             unique=false,
 *             nullable=true
 *         )
 *     )
 * })
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 */
class User extends BaseUser
{
//..

走るとき php bin/console doctrine:schema:update --force データベースでユーザー名を否定できます。

2番, 、フォームタイプ appbundle form restiolationType, 、フォームからユーザー名を削除します。

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->remove('username');
        // you can add other fields with ->add('field_name')
    }

今、あなたは見ることができません ユーザー名 フォームのフィールド(ありがとう $builder->remove('username');)。フォームを送信すると、検証エラーが表示されません "ユーザー名を入力してください" もう必要ないので(注釈のおかげ)。

ソース: https://github.com/friendsofsymfony/fosuserbundle/issues/982#issuecomment-12931663

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top