我正在使用 FOS用户包 并覆盖了 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.phpgetName 方法。

你可以通过以下方式得到它:

$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 处的 true 来多层获取它, get('registration_form_name[email]', null, true); 你也可以做 $email = $request->get('registration_form_name')['email']; (如果你有 php 5.4+)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top