Search code examples
phpsymfonysymfony-securitysymfony-2.7

What should be the default value for $security?


I'm working on this method:

public function loginAction(Request $request, Security $security)
{
    $session = $request->getSession();
    $session->remove('admin_project_id');

    if ($security->has(Security::AUTHENTICATION_ERROR)) {
        $error = $request->attributes->get(Security::AUTHENTICATION_ERROR);
    } else {
        $error = $session->get(Security::AUTHENTICATION_ERROR);
        $session->remove(Security::AUTHENTICATION_ERROR);
    }

    return $this->render('PDOneBundle:Login:index.html.twig',
        array_merge($this->defaultViewParams(), array(
            'last_username' => $session->get(Security::LAST_USERNAME),
            'error'         => $error,
            'include_sidebar' => false,
            )
        )
    );
}

But I got this error when it's called:

Controller "GroupDCA\PDOneBundle\Controller\LoginController::loginAction()" requires that you provide a value for the "$security" argument (because there is no default value or because there is a non optional argument after this one).

What should be the default value for that argument? Is the way I'm using right?


Solution

  • first of all, you don't need to pass $security as an argument. The line where you use security, you actually have to access $request and look its attributes for an error.

    Secondly, I saw you tagged the question as symfony 2.7 and since version @2.6 a new, short way of login was introduced:

    public function loginAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');
    
        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
    
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();
    
        return $this->render(
            'security/login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $lastUsername,
                'error'         => $error,
            )
        );
    }
    

    You can read more from where this piece of code was taken: How to Build a Traditional Login Form