你應該寫事件偵聽器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
或(在我oppinion更好的方式)覆蓋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'))
;
}
}
現在您的應用程序已經準備好手動設置電子郵件。
來源
2013-08-05 21:14:16
NHG
只要他使用相同的表單,驗證將始終失敗 – ferdynator
@ byf-ferdy我添加了「如何編碼?」。 – NHG