【问题标题】:Symfony: pass parameter between actions (with a redirect)Symfony:在动作之间传递参数(带有重定向)
【发布时间】:2011-03-08 07:15:21
【问题描述】:
我正在从一个动作 (executeProcess) 重定向到另一个动作 (executeIndex)。我希望能够在不使用 GET 的情况下传递参数/变量(例如 $this->redirect('index', array('example'=>'true')))
有没有一种方法可以直接传递参数而不直接显示在 URL 中? (例如 POST)。谢谢。
【问题讨论】:
标签:
parameter-passing
symfony-1.4
【解决方案1】:
在两个动作之间传递变量的最佳方式是使用FlashBag
public function fooAction() {
$this->get('session')->getFlashBag()->add('baz', 'Some variable');
return $this->redirect(/*Your Redirect Code to barAction*/);
}
public function barAction() {
$baz = $this->get('session')->getFlashBag()->get('baz');
}
要在 Twig 模板中使用变量,请使用这个 --
{% for flashVar in app.session.flashbag.get('baz') %}
{{ flashVar }}
{% endfor %}
【解决方案2】:
为什么不使用会话在重定向之前存储值,然后在重定向后将它们用于其他操作?喜欢:
class ActionClass1 extendes sfActions
{
public function executeAction1(sfWebRequest $request)
{
[..]//Do Some stuff
$this->getUser()->setAttribute('var',$variable1);
$this->redirect('another_module/action2');
}
}
class ActionClass2 extends sfActions
{
public function executeAction2(sfWebRequest $request)
{
$this->other_action_var = $this->getUser()->getAttribute('var');
//Now we need to remove it so this dont create any inconsistence
//regarding user navigation
$this->getUser()->getAttributeHolder()->remove('var');
[...]//Do some stuff
}
}
【解决方案3】:
另一种不重定向浏览器的解决方案
class someActionClass extends sfActions{
function myExecute(){
$this->getRequest()->setParameter('myvar', 'myval');
$this->forward('mymodule', 'myaction')
}
}
//Here are your actions in another module
class someActionClass2 extends sfActions{
function myExecute2(){
$myvar = $this->getRequest()->getParameter('myvar');
}
}
`