我尝试学习使用Symfony 3.1.10创建一个网站。为了帮助我创建登录/注册项目,我决定使用捆绑包" FOSUserBundle 2.0"。所以现在我创建一个自定义表单(我按名称字段更改了用户名字段)。对于我的项目,我试图允许只注册具有特定电子邮件地址的用户。因此经过一些研究,他们解释了创建自定义行为,FOSUserbundle创建了事件。所以,当我有REGISTRATION_SUCCESS时,我会创建自定义事件监听器,如下所示。
class CheckEmailBefore implements EventSubscriberInterface {
private $router;
private $request;
public function __construct(RouterInterface $router,Request $request)
{
$this->router = $router;
$this->request = $request;
}
public static function getSubscribedEvents() {
return [
FOSUserEvents::REGISTRATION_SUCCESS => 'onCheck'
];
}
/**
* @param FormEvent $event
*
*/
public function onCheck(FormEvent $event){
$user = $event->getForm()->getData();
$email = $user->getEmailCanonical();
$format = explode("@",$email);
if((strcmp($format[1] , "truc.com")===0) || (strcmp($format[1] , "chose.com") === 0)){
$url = $this->router->generate('list');
$response = new RedirectResponse($url);
$event->setResponse($response);
}else{
$event->getForm()->addError(new FormError("Enter a mail address with valid format"), 1);
var_dump($event->getForm()->getErrors());
die("Address is not valid");
}
}
}
我的问题是,一旦我添加错误,我不知道如何在我的表单上显示它,就像捆绑包已经创建的错误一样。
提前致谢。
答案 0 :(得分:0)
我不会为此使用Event Dispatcher组件,我只是简单地创建一个自定义验证约束。这是the link to the docs。
您可以创建一个约束,以检查您的用户是否在其电子邮件中包含特定域。如果约束未通过,则验证将失败,从而导致注册过程失败,从而为您提供正确的错误信息。
文档解释得非常好,但如果您需要实施方面的帮助,请告诉我,我可以更新我的答案。
更新:
class RegistrationForm extends OtherForm
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('firstName', TextType::class, [
'required' => true,
'constraints' => [
new NotBlank(),
new Length(['min' => 2, 'max' => 20]),
]
])
->add('lastName', TextType::class, [
'required' => true,
'constraints' => [
new NotBlank(),
new Length(['min' => 2, 'max' => 20]),
]
])
->add('secondLastName', TextType::class, [
'required' => true,
'constraints' => [
new NotBlank(),
new Length(['min' => 2, 'max' => 20]),
]
])
->add('email', TextType::class, [
'required' => true,
'constraints' => [
new NotBlank(),
new CustomConstraint(),
new Length(['min' => 2, 'max' => 20]),
]
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
'csrf_protection' => false,
'allow_extra_fields' => true,
]);
}