How to pass an array as a parameter to a controller action using Symfony 2? Could you write an example of how to define a route that contains an unknown length array as a parameter. For example, url: http: // localhost: 8000 / blog / post /? Tags = [tag1, tag2, tag3] , where the number of tags varies from 0 to 100. There is also an example controller for this route, where the action returns the values โโof the tag array.
Using the following encoding (see routing.yml and controller.php below), I get an error message:
Catchable Fatal Error: Argument 3 passed to Symfony\Component\Routing\Route::__construct() must be of the type array, string given, called in C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\vendor\symfony\symfony\src\Symfony\Component\Routing\Loader\YamlFileLoader.php on line 147 and defined in C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\app/config\routing.yml (which is being imported from "C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\app/config/routing_dev.yml").
URL:
http://localhost:8000/blog/post/tag1 http://localhost:8000/blog/post/tag1/tag2/tag3/tag4 http://localhost:8000/blog/post/?tags=[tag1,tag2]
Below are the various combinations of routing and controller files that I have tried so far:
// version r1, routing.yml
blog_post_tags: path: blog/post/{tags} defaults: { _controller: DefaultController:list_postsByTagActionQ } requirements: tags : "[a-zA-Z0-9,]+"
// r2 version, routing.yml
blog_post_tags: resource: "@BlogBundle/Controller/" type: annotation prefix: /blog/ defaults: { _controller: DefaultController:list_postsByTagActionQ }
// version r1,2-c1, controller.php
//http://localhost:8000/blog/post/?tags=[tag1,tag2] . /** * @Route("/posts/{tags}") * @Template() */ public function list_postsByTagAction($tags){ var_dump($tags); return array('posts'=>['post1','post2']); }
// version r1,2-c2, controller.php
//url http://localhost:8000/blog/post/?tags=[tag1,tag2] /** * @Route("/posts/{tags}") * @Method("GET") * @Template() */ public function list_postsByTagActionQ1(Request $request){ $tags=$request->query->get('tags'); // get a $_GET parameter var_dump($tags); return array('posts'=>['post1','post2']); }
// version r1,2-c3, controller.php
//url http://localhost:8000/blog/post/?tags=[tag1,tag2] /** * @Route("/posts/{tags}") * @Method("GET") * @Template() */ public function list_postsByTagActionQ3(Request $request, $tags){ var_dump($tags); return array('posts'=>['post1','post2']); }
// version r3, routing.yml
blog_post_tags: path: blog/post/{tags} defaults: { _controller: DefaultController:list_postsByTagActionQ }
// version r3-c4, controller.php
//url http://localhost:8000/blog/post/?tags=[tag1,tag2] public function list_postsByTagActionQ(Request $request){ $tags=$request->query->get('tags'); // get a $_GET parameter var_dump($tags); }