【问题标题】:Symfony2 OneToMany Relation - get object via hidden form field?Symfony2 OneToMany Relation - 通过隐藏的表单字段获取对象?
【发布时间】:2014-03-21 07:36:27
【问题描述】:

我目前正在 Symfony 中开发一个小型网站,访问者可以在其中评论人道主义项目。一个项目可以有多个 cmets(oneToMany 关系)。

在 Project show.html.twig 页面上,我正在呈现 Comment 新表单。

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

现在,如果有人创建评论,我需要指定当前显示的项目。项目通过路由显示:

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

这里是 cmets 的创建控制器:

 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(),
        ));
    }

我知道有两种选择:

  1. 在表单中添加一个包含项目 ID 的隐藏字段。
  2. 在路由中包含您的项目 ID(因此也作为操作参数)。

但我仍在努力让项目对象将其分配给评论。选项 1 将如何工作?如何让当前项目进入隐藏字段表单?

已经谢谢了!

【问题讨论】:

    标签: php symfony doctrine symfony-forms


    【解决方案1】:

    试试这个:

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

    在您的表单模板中添加:

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

    【讨论】:

    • 如何将 id 从 new 转移到 create 方法?我现在收到以下错误消息:控制器“DbeDddddBundle\Controller\CommentController::createAction()”要求您为“$id”参数提供一个值(因为没有默认值或因为后面有一个非可选参数这个)。
    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多