【问题标题】:Symfony2, How to pass array as parameter to controller action?Symfony2,如何将数组作为参数传递给控制器​​动作?
【发布时间】:2016-02-09 07:13:08
【问题描述】:

如何使用 Symfony 2 将数组作为参数传递给控制器​​操作?您能否写一个如何定义路由的示例,其中包含未知长度数组作为参数。例如 url:http://localhost:8000/blog/post/?tags=[tag1,tag2,tag3],其中标签的数量从 0 到 100 不等。 也是此路由的示例控制器,其中操作返回标签数组的值。

使用以下编码(参见下面的 routing.yml 和 controller.php)我得到了错误:

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").

网址:

http://localhost:8000/blog/post/tag1
http://localhost:8000/blog/post/tag1/tag2/tag3/tag4
http://localhost:8000/blog/post/?tags=[tag1,tag2]

以下是迄今为止我尝试过的路由和控制器文件的不同组合:

//版本r1,routing.yml

blog_post_tags:
    path: blog/post/{tags}
    defaults: { _controller: DefaultController:list_postsByTagActionQ }
    requirements:
        tags : "[a-zA-Z0-9,]+"

//版本r2,routing.yml

blog_post_tags:
    resource: "@BlogBundle/Controller/"
    type:     annotation
    prefix:   /blog/
    defaults: { _controller: DefaultController:list_postsByTagActionQ } 

//版本 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']);
}

//版本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']);
} 

//版本 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']);
}

//版本r3,routing.yml

blog_post_tags:
    path: blog/post/{tags}
    defaults: { _controller: DefaultController:list_postsByTagActionQ }

//版本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);
}

【问题讨论】:

标签: symfony routes


【解决方案1】:

好吧,经过一些尝试,我找到了下一个解决方案。

您可以更改路由模式到此(标签:“[a-zA-Z0-9/]+”):

blog_post_tag:
    path: blog/post/{tags}
    defaults: { _controller: DefaultController:list_postsByTagActionQ }
    requirements:
        tags : "[a-zA-Z0-9\/]+"

然后你可以传递http://localhost:8000/blog/post/tag1/tag2/tag3/tag4,但是你仍然需要explode()来获取参数。

【讨论】:

  • 我完全删除了要求,但我得到了同样的错误。
  • 你的文件是用 utf-8 保存的吗?也许你在“要求”键之后有不可见的字符..比如换行符?尝试删除需求并从头开​​始重新编写。
  • 版本 r2 和版本 r3 没有要求
  • @olga 所以,你总是得到错误“可捕获的致命错误:参数 3 传递给 Symfony\Component\Routing\Route::__construct()...”?
【解决方案2】:

终于,我找到了答案。与其传递数组,不如将其编码为 json 字符串。这是一个例子:

C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Controller\UserController.php

..
    /**
     * Displays a form to edit an existing User entity.
     *
     * @Route("/{id}/edit", name="user_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, User $user)
    {
..
 $bredArr=array( 'user_edit' => array (  'id'=>$user->getId() ) );
..
        return $this->render( 'MeetingBundle::user/edit.html.twig', array(
            'user' => $user,
            'edit_form' => $editForm->createView(),
            'image_form' => $imageForm->createView(),
            'delete_form' => $deleteForm->createView(),
            'bredArr'=>$bredArr,
        ));

C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Controller\ImageController.php ..

   /**
     * Deletes a Image entity without displaying forms. nf = no forms
     *
     * @Route("/{id}/deletenf/{bredArrJ}", name="image_deletenf")
     * @Method("GET|POST")
     */    
     public function deletenfAction(Request $request, $id, $bredArrJ) 
     {

        $bredArr=json_decode($bredArrJ, $assoc = true);

            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MeetingBundle:Image')->find($id);
            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Image entity.');
            }
            $em->remove($entity);
            $em->flush();  

            if(array_key_exists('image_delete', $bredArr)) {
                return $this->redirect($this->generateUrl('image_index'));
            }
            else if (array_key_exists('user_edit', $bredArr)){
                return $this->redirect( $this->generateUrl('user_edit', array( 'id'=>$bredArr['user_edit']['id'] ) ) );
            }     
            else if {
                //redirect to other pages according key in $bredArr
            }
     }    

C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Resources\views\user\edit.html.twig

{# dispplays user, user_delete and image uplaod forms, also shows images which belongs to user, retrieving them via ManyToMany realation in User entity field "imgsuni" #}
 {% for img in user.imgsuni %}
 <br> {% include 'MeetingBundle:user:userimg.html.twig' %}
 {% endfor %}

C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Resources\views\user\userimg.html.twig

<img src="{{ asset( 'bundles/meeting/images/uploads/'~img.path~'' ) }}" height="100" />
<br><a href="{{  path('image_deletenf', { 'id': img.id,  'bredArrJ' : bredArr|json_encode }) }}"> Delete image </a>
"{{ img.title }}".

$bredArr 是在User 控制器edit_user 操作中创建的变量。它用作路径变量image_deletenf 中的参数。我不知道如何将它作为数组传递,但如果编码为 Json 字符串,它就可以工作。我需要image_deletenf 操作,以便能够重定向到我想要的路径。我可以从用户、事件和评论实体中删除图像,因此在删除后我想回到用户、事件或评论而不是默认的 image_index,因此我需要这个 $bredArr 以使用正确的参数指向正确的实体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多