Symfony2 将 Recaptcha 添加到 FOSUserBundle 登录页面

Symfony2 Adding Recaptcha to FOSUserBundle Login Page

我正在尝试将 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()

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

替换

$this->createForm(

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