[英]Pass variable from controller to another in Symfony?
I have 2 actions functions in my controller and I want to pass variable to an other action function 我的控制器中有2个动作函数,我想将变量传递给其他动作函数
This is my first function in my controller 这是我在控制器中的第一个功能
public function newUserAction(Request $request)
{ .........
$url = $this->generateUrl('userBundle_new_user_reasonCodeAjaxView',
array('id' => $newUser->getCode(),
'countCode' => $countCode,));
return $this->redirect($url);
This my second funtion in my controller 这是我控制器中的第二个功能
public function userCodeAjaxViewAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$pc = $em->getRepository('UserBundle:Code')->find($id);
if($pc != null)
{
return $this->render('UserBundle:userCodeView.html.twig', array(
'pc' => $pc,
));
}
And my twif looks like this 我的twif看起来像这样
<div class="">
<div class="panel panel-default step3-textarea top-arrow top-arrow">
<div class="panel-body">
<fieldset>
<div>
{{ pc.name|trans }}
{{countCode}}
</div>
</fieldset>
</div>
</div>
</div>
I am getting an error Variable "countCode" does not exist in...
我收到错误
Variable "countCode" does not exist in...
Is there any idea how I can use a variable from a controller in a other controller? 有什么想法我如何使用其他控制器中的控制器变量?
You are using the same template scope for the two controllers, and this is not possible. 您正在为两个控制器使用相同的模板范围,这是不可能的。 If you are using two controllers to render two simple informations, why not simply returning a JSON and displaying it in a more global template using AJAX ?
如果您使用两个控制器来呈现两个简单的信息,为什么不简单地返回JSON并使用AJAX在更全局的模板中显示它?
Else a pure symfony solution would be to have a main template view.html.twig
where you would put 另外一个纯粹的symfony解决方案是将一个主模板
view.html.twig
放在哪里
<div class="">
<div class="panel panel-default step3-textarea top-arrow top-arrow">
<div class="panel-body">
<fieldset>
<div>
{{ render(controller("AppBundle:UserController:newUserAction")) }}
{{ render(controller("AppBundle:UserController:userCodeAjaxViewAction")) }}
</div>
</fieldset>
</div>
</div>
Given that then your two controller action templates would be simple {{ pc.name|trans }}
and {{countCode}}
. 鉴于此,您的两个控制器操作模板将是简单的
{{ pc.name|trans }}
和{{countCode}}
。
Hope it helps you out ! 希望它可以帮到你!
You can not get a variable from another controller. 您无法从另一个控制器获取变量。
Every request creates only one controller instance. 每个请求只创建一个控制器实例。
What you can do is create a Service that you can call in the controller. 您可以做的是创建一个可以在控制器中调用的服务。
Something like that: 像这样的东西:
class CountUserService{
public function count(){
return 1; // count users here
}
}
And the in the controller do this: 并在控制器中执行此操作:
$service = new CountUserService();
$data=['countCode' => $service->count()];
return $this->render('UserBundle:userCodeView.html.twig', $data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.