Symfony2 / Symfony3에서 FOSUserBundle을 사용하여 사용자 이름 필드를 이메일로 제거 / 척
로그인 모드로 이메일 만 받고 싶습니다. 사용자 이름은 갖고 싶지 않습니다. symfony2 / symfony3 및 FOSUserbundle로 사용할 수 있습니까?
나는 여기에서 읽었다. http://groups.google.com/group/symfony2/browse_thread/thread/92ac92eb18b423fe
그러나 나는 두 가지 제약에 제약이 있습니다.
문제는 사용자가 이메일 주소를 비워두면 두 가지 제약 조건 위반이 발생하는 것입니다.
- 사용자 이름을 입력 해주세요
- 이메일을 입력하세요
주어진 필드에 대한 유효성 검사를 주어진 방법이 있습니까? 아니면 양식에서 필드를 완전히 제거하는 더 좋은 방법이 있습니까?
수행해야 할 작업에 대한 전체 개요
다음은 수행해야 할 작업에 대한 전체 개요입니다. 이 게시물의 끝 부분에 여기 저기에서 다양한 소스를 제공했습니다.
1. 세터 재정의 Acme\UserBundle\Entity\User
public function setEmail($email)
{
$email = is_null($email) ? '' : $email;
parent::setEmail($email);
$this->setUsername($email);
return $this;
}
2. 양식 유형에서 사용자 이름 필드를 제거합니다.
( RegistrationFormType
및 모두 ProfileFormType
)
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
합니다. 생성 할 새 유효성 검사 그룹은 AcmeRegistration
및 AcmeProfile
입니다. 따라서 우리는 제공하는 것을 완전히 무시하고 있습니다 FOSUserBundle
.
3.a. 의 구성 파일 업데이트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. 끝
그게 다야! 당신은 잘 가야합니다!
이 게시물에 사용 된 문서 :
- FOSUserBundle에서 사용자 이름을 제거하는 가장 좋은 방법
- [유효성 검사] 제대로 재정의되지 않음 발생
- UniqueEntity
- Fosuserbundle 등록 양식 확인
- Symfony에서 유효성 검사 그룹을 사용하는 방법
- 유효성 검사 그룹을 형식으로 사용하는 Symfony2
여기에 설명 된 등록 및 프로필 양식 유형을 모두 재정의 하고 사용자 이름 필드를 제거 하여이 작업을 수행 할 수 있습니다.
$builder->remove('username');
내 구체적인 사용자 클래스에서 setEmail 메소드를 재정의하는 것과 함께 :
public function setEmail($email)
{
$email = is_null($email) ? '' : $email;
parent::setEmail($email);
$this->setUsername($email);
}
Michael이 지적했듯이 사용자 지정 유효성 검사 그룹에서이를 수 있습니다. 예를 들면 :
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부터 빠른 해결 방법 은 사용자 이름을 BaseUser를 확장하는 사용자 클래스의 _construct에있는 클래스로 설정하는 것입니다.
public function __construct()
{
parent::__construct();
$this->username = 'username';
}
이렇게하면 유효성 검사기가 위반을 트리거하지 않습니다. 그러나 Patt가 게시 한 사용자 이름으로 이메일을 설정하는 것을 잊지 않고 .
public function setEmail($email)
{
$email = is_null($email) ? '' : $email;
parent::setEmail($email);
$this->setUsername($email);
}
사용자 : 사용자 이름에 대한 참조를 위해 다른 파일을 확인하고 그에 따라 변경해야합니다.
유효성 검사를 사용자 지정해 보거나?
이렇게 상속 된 UserBundle에서 상속 된 고유 한 구성이 있고 Resources / config / validation.xml 복사 / 조정해야합니다. 또한 config.yml의 validation_groups를 사용자 지정 유효성 검사로 설정해야합니다.
Validation을 대체하는 대신 RegistrationFormHandler # process를 대체하는 것을 선호하고,보다 정확하게 원본 메서드의 복사 본인 새 메서드 processExtended (예 :)를 추가하고 RegistrationController에서 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 유효성 검사 규칙을 선호합니다. 등록 양식의 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 \ 엔티티 \ 사용자 , 사용자 클래스 위의 주석을 추가
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
데이터베이스에서 사용자 이름을 nullable로 만듭니다.
둘째 , 양식 유형 AppBundle \ Form \ RegistrationType 에서 양식 에서 사용자 이름을 제거합니다.
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
'ProgramingTip' 카테고리의 다른 글
New Intent ()는 Android에서 새 인스턴스를 시작합니다. launchMode =“singleTop” (0) | 2020.12.15 |
---|---|
특정 시간의 시간 가져 오기 (0) | 2020.12.15 |
ImageMagick 사용 대리자 없음 (0) | 2020.12.15 |
xcode에서 메서드 드롭 다운을 여는 바로 가기 (0) | 2020.12.15 |
Java Import 오기는 어떻게 작동합니까? (0) | 2020.12.15 |