Preciel
Preciel

Reputation: 2827

FosUserBundle controller override

[SETTINGS]

[PROBLEM]

While reading the Symfony doc about how to override any part if a bundle,
I met those lines:

If the controller is a service, see the next section on how to override it. Otherwise, define a new route + controller with the same path associated to the controller you want to override (and make sure that the new route is loaded before the bundle one).

And somehow felt overjoyed seeing how the doc was still as incomplete as ever on some of the most important sections... Right, this part got no code example, can't even be sure of what to do.

Would someone be kind enough to give me an example on how to override the FosUserBundle? Just one section like the login part will be enough. As the same logic will apply for the other sections.

Also, as a side questions:

Upvotes: 2

Views: 701

Answers (1)

Philippe-B-
Philippe-B-

Reputation: 636

What I understand : simply create your controller and then add a route for it in your configuration with the same path as the one you want to override, making sure it's loaded before.

For example, to override the login action:

// AppBundle\Controller\UserController.php

/**
 * @route("/login", name="login_override")
 * @param Request $request
 * @return Response
 */
public function loginAction(Request $request)
{
    /** @var $session Session */
    $session = $request->getSession();

    $authErrorKey = Security::AUTHENTICATION_ERROR;
    $lastUsernameKey = Security::LAST_USERNAME;

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

    if (!$error instanceof AuthenticationException) {
        $error = null; // The value does not come from the security component.
    }

    // last username entered by the user
    $lastUsername = (null === $session) ? '' : $session->get($lastUsernameKey);

    $tokenManager = $this->container->get('security.csrf.token_manager');

    $csrfToken = $tokenManager
        ? $tokenManager->getToken('authenticate')->getValue()
        : null;

    return $this->render('@FOSUser/Security/login.html.twig', array(
        'last_username' => $lastUsername,
        'error' => $error,
        'csrf_token' => $csrfToken,
    ));
}


#app\config\routing.yml
app:
    resource: '@AppBundle/Controller/'
    type: annotation

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

Upvotes: 1

Related Questions