问题
In Symfony, after a user successfully log out, how to display a success message like "you have successfully logged out" ?
回答1:
1) Create a new service to handle the logout success event.
In services.yml
add the service:
logout_success_handler:
class: Path\To\YourBundle\Services\LogoutSuccessHandler
arguments: ['@security.http_utils']
And add the class, replacing /path/to/your/login
with the url of your login page (in the last line of the controller):
<?php
namespace Path\To\YourBundle\Services;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
class LogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
protected $httpUtils;
protected $targetUrl;
/**
* @param HttpUtils $httpUtils
*/
public function __construct(HttpUtils $httpUtils)
{
$this->httpUtils = $httpUtils;
$this->targetUrl = '/path/to/your/login?logout=success';
}
/**
* {@inheritdoc}
*/
public function onLogoutSuccess(Request $request)
{
$response = $this->httpUtils->createRedirectResponse($request, $this->targetUrl);
return $response;
}
}
2) Configure your security.yml
to use the custom LogoutSuccessHandler
just created:
firewalls:
# ...
your_firewall:
# ...
logout:
# ...
success_handler: logout_success_handler
3) In the twig template of your login page add:
{% if app.request.get('logout') == "success" %}
<p>You have successfully logged out!</p>
{% endif %}
回答2:
Imho, there is a definitively simpler way. In security.yaml
, define a route to redirect to after logout thanks to the target
key :
security:
firewalls:
main:
[...]
logout:
path: /logout
target: /logout_message
Then in a controller (SecurityController.php
is fine for this), define this action, wich only add the flash message and then redirect where you want (home in this exemple) :
/**
* @Route("/logout_message", name="logout_message")
*/
public function logoutMessage()
{
$this->addFlash('success', "You've been disconnected. Bye bye !");
return $this->redirectToRoute('home');
}
来源:https://stackoverflow.com/questions/41062805/symfony-how-to-display-a-success-message-after-logout