繁体   English   中英

如何从FOSUserBundle注册表单获取表单数据?

[英]How can I get the form data from the FOSUserBundle registration form?

我正在使用FOSUserBundle并覆盖了RegistrationController 表单提交并有效后,我想获取用户在注册表单中输入的电子邮件地址。

但是我看不到任何办法。 Symfony2表单文档中获取的信息 ,您可以像这样获得表单数据:

$this->get('request')->request->get('name');

但是RegistrationController不知道get()方法(因为它不是从Symfony2控制器实体继承的)。 所以我可以这样:

// Note the ...->container->...
$this->container->get('request')->request->get('name');

但这返回NULL 现在,我尝试从$form获取它。

// Does contain a lot of stuff, but not the entered email address
$form->get('email');

// Does also contain a lot of stuff, but not the desired content
$request->get('email');
$request->request('email');

// Throws error message: No method getData()
$request->getData();

任何想法?

非常非常简单。 您创建具有相关实体的表单。 在FOSUserBundle中,您应该具有RegistrationFormHandler ,并且在process方法中,您需要:

$user = $this->createUser();
$this->form->setData($user);
if ('POST' === $this->request->getMethod()) {
     $this->form->bind($this->request);
     if ($this->form->isValid()) /**(...)**/

$this->form->bind($this->request)$user对象中的每个值都被来自表单的数据覆盖。 因此,您可以使用$user->getEmail()

另一方面,您可以直接从请求中获取数据,而不是通过属性名称,而是通过表单名称。 在FOSUserBundle注册表单中,它称为fos_user_registration您可以在FOS/UserBundle/Form/Type/RegistrationFormType.php中的getName方法中找到它。

您可以通过以下方式获得它:

$registrationArray = $request->get('fos_user_registration');
$email = $registrationArray['email'];

如果要使用控制器即服务(应该与此一起使用),则可以在构造函数中传递RequestStack(sf> = 2.4)并执行$this->request_stack->getCurrentRequest()->get();

我的猜测是您正在尝试获取POST数据。 您正在尝试将数据放入我假定的表单对象中。 我建议您看看: http : //symfony.com/doc/current/book/forms.html(如果您有自定义表单)。

关于您的问题,表格可能包含名称。 如果您想直接访问它而不是在表单中执行操作,则需要直接在$ deep, get('registration_form_name[email]', null, true);处通过true来多层获取它get('registration_form_name[email]', null, true); 您也可以执行$email = $request->get('registration_form_name')['email']; (如果您使用的是PHP 5.4+)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM