php Symfony2:重定向到最后一条路线并闪现一条消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11892080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symfony2: Redirecting to last route and flash a message?
提问by vinnylinux
I'm having a small problem when trying to flash a message and redirect the user back to the previous page in Symfony 2.
我在尝试闪现一条消息并将用户重定向回Symfony 2 中的上一页时遇到了一个小问题。
I have a very simple CRUD. When new, or edit, i want to flash a message if something goes wrong in the respective create/update methods:
我有一个非常简单的 CRUD。新建或编辑时,如果相应的创建/更新方法出现问题,我想闪烁一条消息:
User --GET--> newnew --POST--> create (fails)--REDIRECT--> new (with flash message)
User --GET--> newnew --POST--> create (fails)--REDIRECT--> new (with flash message)
I'm doing the following:
我正在做以下事情:
$this->container->get('session')->setFlash('error', 'myerror');
$referer = $this->getRequest()->headers->get('referer');
return new RedirectResponse($referer);
However, it's not redirecting to the correct referrer! Even though the value of referrer is correct (eg.: http://localhost/demo/2/edit/) It redirects to the index. Why?
但是,它不会重定向到正确的引用者!即使 referrer 的值是正确的(例如:)http://localhost/demo/2/edit/它也会重定向到索引。为什么?
采纳答案by Flip
This is an alternative version of Naitsirch and Santi their code. I realized a trait would be perfect for this functionality. Also optimized the code somewhat. I preferred to give back all the parameters including the slugs, because you might need those when generating the route.
这是 Naitsirch 和 Santi 代码的替代版本。我意识到一个特征对于这个功能来说是完美的。也稍微优化了代码。我更喜欢返回包括 slug 在内的所有参数,因为在生成路由时您可能需要这些参数。
This code runs on PHP 5.4.0 and up. You can use the trait for multiple controllers of course. If you put the trait in a seperate file make sure you name it the same as the trait, following PSR-0.
此代码在 PHP 5.4.0 及更高版本上运行。当然,您可以将 trait 用于多个控制器。如果您将特征放在单独的文件中,请确保将其命名为与特征相同的名称,遵循 PSR-0。
<?php
trait Referer {
private function getRefererParams() {
$request = $this->getRequest();
$referer = $request->headers->get('referer');
$baseUrl = $request->getBaseUrl();
$lastPath = substr($referer, strpos($referer, $baseUrl) + strlen($baseUrl));
return $this->get('router')->getMatcher()->match($lastPath);
}
}
class MyController extends Controller {
use Referer;
public function MyAction() {
$params = $this->getRefererParams();
return $this->redirect($this->generateUrl(
$params['_route'],
[
'slug' => $params['slug']
]
));
}
}
回答by Kisz Na
For symfony 3.0,flash message with redirection back to previous page,this can be done in controller.
对于 symfony 3.0,带有重定向回上一页的闪存消息,这可以在控制器中完成。
$request->getSession()
->getFlashBag()
->add('notice', 'success');
$referer = $request->headers->get('referer');
return $this->redirect($referer);
回答by Santi
The message from Naitsirch presented in the next url: https://github.com/symfony/symfony/issues/2951
来自 Naitsirch 的消息显示在下一个 url:https: //github.com/symfony/symfony/issues/2951
Seems a good solution for that you need:
似乎是您需要的一个很好的解决方案:
public function getRefererRoute()
{
$request = $this->getRequest();
//look for the referer route
$referer = $request->headers->get('referer');
$lastPath = substr($referer, strpos($referer, $request->getBaseUrl()));
$lastPath = str_replace($request->getBaseUrl(), '', $lastPath);
$matcher = $this->get('router')->getMatcher();
$parameters = $matcher->match($lastPath);
$route = $parameters['_route'];
return $route;
}
Then with a redirect:
然后使用重定向:
public function yourFunctionAction()
{
$ruta = $this->getRefererRoute();
$locale = $request->get('_locale');
$url = $this->get('router')->generate($ruta, array('_locale' => $locale));
$this->getRequest()->getSession()->setFlash('notice', "your_message");
return $this->redirect($url);
}
回答by Victor Odiah
This works for me:
这对我有用:
$this->redirect($request->server->get('HTTP_REFERER'));
回答by moldcraft
I have similar functionality on my site. It is multilingual. Articles exists only in a single locale. When the user will try to switch to other locale, it should redirect back to previous page and flash message that that page/article doesn't exist on the requested locale.
我的网站上有类似的功能。它是多语言的。文章仅存在于单个语言环境中。当用户尝试切换到其他语言环境时,它应该重定向回上一页并显示该页面/文章在请求的语言环境中不存在的消息。
/en/article/3 -> /fr/article/3 (404) -> Redirect(/en/article/3)
Here is my version of the script that works well on devand prodenvironments:
这是我上行之有效的脚本的版本dev和prod环境:
$referer = $request->headers->get('referer')
// 'https://your-domain.com' or 'https://your-domain.com/app_dev.php'
$base = $request->getSchemeAndHttpHost() . $request->getBaseUrl();
// '/en/article/3'
$path = preg_replace('/^'. preg_quote($base, '/') .'/', '', $referer);
if ($path === $referer) {
// nothing was replaced. referer is an external site
} elseif ($path === $request->getPathInfo()) {
// current page and referer are the same (prevent redirect loop)
} else {
try {
// if this will throw an exception then the route doesn't exist
$this->container->get('router')->match(
// '/en/hello?foo=bar' -> '/en/hello'
preg_replace('/\?.*$/', '', $path)
);
// '/app_dev.php' . '/en/article/3'
$redirectUrl = $request->getBaseUrl() . $path;
return new RedirectResponse($redirectUrl);
} catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {}
}
回答by Thomas Kelley
I just set up a simple app, and it seems to work fine. My createAction() looks like this:
我刚刚设置了一个简单的应用程序,它似乎运行良好。我的 createAction() 看起来像这样:
public function createAction()
{
$entity = new Pokemon();
$request = $this->getRequest();
$form = $this->createForm(new PokemonType(), $entity);
$form->bindRequest($request);
if ($entity->getName() == "pikachu")
{
$this->container->get("session")->setFlash("error", "Pikachu is not allowed");
$url = $this->getRequest()->headers->get("referer");
return new RedirectResponse($url);
}
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('pokemon_show', array('id' => $entity->getId())));
}
return $this->render('BulbasaurBundle:Pokemon:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
The flow goes:
流程如下:
- User navigates to /new
- User enters invalid option of "pikachu"
- User clicks submit (POSTs to /create)
- Application rejects the entry, adds flash message, and redirects back to /new
- User sees /new with the flash message
- 用户导航到 /new
- 用户输入无效的“皮卡丘”选项
- 用户点击提交(POSTs 到/create)
- 应用程序拒绝输入,添加 flash 消息,并重定向回 /new
- 用户看到带有 flash 消息的 /new
A few things to check:
需要检查的几件事:
Is your route for
/demo/{entityId}/editactually working? (i.e. if you enter it in the browser, does it actually go to where you expect it to?)Are you chaining together different redirects/forwards? I've noticed that I get unexpected (but correct) behavior when I have a controller that redirects to a URL, and the controller responsible for that URL also redirects somewhere else. I've fixed this issue by using forwards instead.
你的路线是
/demo/{entityId}/edit实际工作吗?(即,如果您在浏览器中输入它,它实际上会到达您期望的位置吗?)您是否将不同的重定向/转发链接在一起?我注意到当我有一个重定向到 URL 的控制器时,我得到了意外(但正确)的行为,并且负责该 URL 的控制器也重定向到其他地方。我已经通过使用转发解决了这个问题。
That said, if all else fails, you could just use the controller's redirect() method to manage the redirect:
也就是说,如果所有其他方法都失败了,您可以使用控制器的 redirect() 方法来管理重定向:
public function createAction()
{
...
return $this->redirect($this->generateUrl("pokemon_new"));
...
}
回答by ex3v
Here you go, declare this as a service and it will return referer to you wherever and whenever you need it. No traits, no weird dependencies.
在这里,将其声明为服务,它会随时随地将引用返回给您。没有特征,没有奇怪的依赖关系。
class Referer
{
/** @var RequestStack */
private $requestStack;
/** @var RouterInterface */
private $router;
public function __construct(RequestStack $requestStack, RouterInterface $router)
{
$this->requestStack = $requestStack;
$this->router = $router;
}
public function getReferer() : string
{
$request = $this->requestStack->getMasterRequest();
if (null === $request)
{
return '';
}
//if you're happy with URI (and most times you are), just return it
$uri = (string)$request->headers->get('referer');
//but if you want to return route, here you go
try
{
$routeMatch = $this->router->match($uri);
}
catch (ResourceNotFoundException $e)
{
return '';
}
$route = $routeMatch['_route'];
return $route;
}
}
回答by Joseph Hightower
seems like you need to have a payload for your redirect to point to. it seems like obscure concept code to me. I would also advise you to make sure your configuration files point to the correct redirect code snippet. Check your server access file to make sure it has redirects enabled also.
似乎您需要为重定向指向一个有效负载。对我来说,这似乎是晦涩的概念代码。我还建议您确保您的配置文件指向正确的重定向代码片段。检查您的服务器访问文件以确保它也启用了重定向。

