symfony - How return an array from a symfony2 controller action? -
in symfony2 project need call same action in many controllers , action should return simple php array passed twig template these controllers. how can it?
a pratical example can explain situation better.
1.shared controller
// acme/demobundle/controller/metascontroller class metascontroller extends controller { public function metasaction() { $myarray= array(); return $myaarray; } }
page render controller
// acme/demobundle/controller/pagecontroller class pagecontroller extends controller { protected $property = "test"; public function indexaction() { $metas= $this->forward('acmedemobundle:metas:metas'); return $this->render('acmedemobundle:page:index.html.twig', array('property'=>property, 'metas'=>$metas)); } }
when error: controller must response array given.
you should create service
// acme/demobundle/controller/metascontroller class metascontroller { public function metasaction() { $myarray= array(); return $myaarray; } }
declare service in acme\demobundle\resources\config\services.yml
services: demo.metas: class: "acme\demobundle\controller\metascontroller"
then can use in other controller
// acme/demobundle/controller/pagecontroller class pagecontroller extends controller { protected $property = "test"; public function indexaction() { $metas= $this->get('demo.metas')->metas(); return $this->render('acmedemobundle:page:index.html.twig', array('property'=>property, 'metas'=>$metas)); } }
Comments
Post a Comment