您应该为fos_user.registration.initialize
. 从代码文档:
/**
* The REGISTRATION_INITIALIZE event occurs when the registration process is initialized.
*
* This event allows you to modify the default values of the user before binding the form.
* The event listener method receives a FOS\UserBundle\Event\UserEvent instance.
*/
const REGISTRATION_INITIALIZE = 'fos_user.registration.initialize';
有关事件调度程序的更多信息:http://symfony.com/doc/current/components/event_dispatcher/introduction.html
和示例事件侦听器:http ://symfony.com/doc/current/cookbook/service_container/event_listener.html
更新 - 如何编码?
在您的config.yml
(或services.yml
其他扩展名,如xml
, php
)中定义如下服务:
demo_bundle.listener.user_registration:
class: Acme\DemoBundle\EventListener\Registration
tags:
- { name: kernel.event_listener, event: fos_user.registration.initialize, method: overrideUserEmail }
接下来,定义监听类:
namespace Acme\DemoBundle\EventListener;
class Registration
{
protected function overrideUserEmail(UserEvent $args)
{
$request = $args->getRequest();
$formFields = $request->get('fos_user_registration_form');
// here you can define specific email, ex:
$email = $formFields['username'] . '@sth.com';
$formFields['email'] = $email;
$request->request->set('fos_user_registration_form', $formFields);
}
}
注意:当然,您可以通过注入@validator
到侦听器来验证此电子邮件。
现在您应该在注册表单中隐藏email
字段。您可以通过覆盖register_content.html.twig
或(以我认为更好的方式)覆盖 FOS来做到这一点,RegistrationFormType
如下所示:
namespace Acme\DemoBundle\Form\Type;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
use Symfony\Component\Form\FormBuilderInterface;
class RegistrationFormType extends BaseType
{
// some code like __construct(), getName() etc.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// some code for your form builder
->add('email', 'hidden', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
;
}
}
现在您的应用程序已准备好手动设置电子邮件。