Symfony2将Recaptcha添加到FOSUserBundle登录页面

时间:2015-10-29 17:43:53

标签: symfony fosuserbundle recaptcha

我正在尝试将reCaptcha添加到我的某个网站的登录名中。

我查看了几个不同的reCaptcha包,最后使用了这个。

https://github.com/dmishh/RecaptchaBundle

添加到注册表单很容易。

然而,在登录表单中添加recaptcha比我希望的要困难得多。

按照github页面上的说明,我将所需的行添加到SecurityController.php:

public function loginAction(Request $request)
{
    /** @var $session \Symfony\Component\HttpFoundation\Session\Session */
    $session = $request->getSession();

    // get the error if any (works with forward and redirect -- see below)
    if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
        $error = $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
    } elseif (null !== $session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
        $error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR);
        $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
    } else {
        $error = '';
    }

    if ($error) {
        // TODO: this is a potential security risk (see http://trac.symfony-project.org/ticket/9523)
        $error = $error->getMessage();
    }
    // last username entered by the user
    $lastUsername = (null === $session) ? '' : $session->get(SecurityContextInterface::LAST_USERNAME);


    $csrfToken = $this->container->has('form.csrf_provider')
        ? $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate')
        : null;


    $recaptcha = $this->createForm($this->get('form.type.recaptcha'));

    return $this->renderLogin(array(
        'last_username' => $lastUsername,
        'error'         => $error,
        'csrf_token' => $csrfToken,
        'recaptcha' => $recaptcha->createView()
    ));
}

但是只是得到以下错误:

FatalErrorException: Error: Call to undefined method FOS\UserBundle\Controller\SecurityController::createForm()

1 个答案:

答案 0 :(得分:2)

因为SecurityController扩展了ContainerAware而不是Controller。

替换

$this->createForm(

通过

$this->container->get('form.factory')->create(