dsjq62428 2014-03-21 07:36
浏览 46

Symfony2 OneToMany Relation - 通过隐藏表单字段获取对象?

I'm currently developing a small website in Symfony where visitors can comment on hummanitarian projects. A project can have many comments (oneToMany relation).

On the Project show.html.twig page I'm rendering the Comment new form.

{{ render(controller('DbeDonaciBundle:Comment:new')) }}

Now if someone creates a comment I need to asign the current displayed project. The project is displayed via a route:

dbe_project_show:
pattern:  /{id}/{name}/show
defaults: { _controller: "DbeDonaciBundle:Project:showProjectWithDetails" }

Here is the create Controller for the comments:

 public function createAction(Request $request)
    {
        $entity = new Comment();


        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);


        if ($form->isValid()) {
            // get current user
            $entity->setUser($this->get('security.context')->getToken()->getUser());

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('dbe_comment_show', array('id' => $entity->getId())));
        }

        return $this->render('DbeDonaciBundle:Comment:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

I know there are two options:

  1. Add a hidden field containing project id to your form.
  2. Have your project id in route (and therefor as action parameter too).

But I'm still struggeling to get the project object to asign it to the comment. How would option 1 work? How do I get the current project into the hidden field form?

Thanks already!

  • 写回答

1条回答 默认 最新

  • dongxun7962 2014-03-21 07:59
    关注

    Try this one:

    {{ render(controller('DbeDonaciBundle:Comment:new',{'id': app.request.get('id')})) }}
    

    In your form template add:

    <input type="hidden" name="id" value="{{ id }}"/>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序