Symfony2:重定向到最后一条路线并闪现一条消息? [英] Symfony2: Redirecting to last route and flash a message?
问题描述
我在 Symfony 2 中尝试闪现消息并将用户重定向回上一页时遇到了一个小问题.
I'm having a small problem when trying to flash a message and redirect the user back to the previous page in Symfony 2.
我有一个非常简单的 CRUD.新建或编辑时,如果相应的创建/更新方法出现问题,我想显示一条消息:
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:
用户--GET-->新的
new --POST-->创建(失败)
--REDIRECT-->新的(带有快闪信息)
我正在做以下事情:
$this->container->get('session')->setFlash('error', 'myerror');
$referer = $this->getRequest()->headers->get('referer');
return new RedirectResponse($referer);
但是,它并没有重定向到正确的推荐人!即使引用的值是正确的(例如:http://localhost/demo/2/edit/
)它也会重定向到索引.为什么?
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?
推荐答案
这是 Naitsirch 和 Santi 代码的替代版本.我意识到一个特征对于这个功能来说是完美的.也稍微优化了代码.我更喜欢返回包括 slug 在内的所有参数,因为您在生成路由时可能需要这些参数.
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.
此代码在 PHP 5.4.0 及更高版本上运行.当然,您可以将 trait 用于多个控制器.如果您将特征放在单独的文件中,请确保将其命名为与特征相同的名称,遵循 PSR-0.
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
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']
]
));
}
}
这篇关于Symfony2:重定向到最后一条路线并闪现一条消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!