dongxu1029 2016-10-15 07:43
浏览 32
已采纳

如何自动将用户对象传递给Symfony 3表单?

I'm learning symphony 3 framework and I ran into a problem that should be basic but I couldn't find a solution yet.

I have an order form, data class is set to the Order object, which is ORM mapped to the according table. I have relations set to User, Product and Payment objects. In my form the user can select product and payment and it would work so far. Only I don't know how to pass the current user object to the form, so it validates. I don't want to put a form field for user in, because it always is the current user object and the user shouldn't be able to see or modify it somehow.

Is there an option besides making the user relation nullable and adding it after form validation and before persisting? Doesn't seem best practice to have this field optional in database.

  • 写回答

1条回答 默认 最新

  • drxt70655 2016-10-15 09:49
    关注

    In this case you don't have to think too difficult. Just set the user entity before persisting the Product entity

    if ($form->isSubmitted() && $form->isValid())
    {
            $em = $this->getDoctrine()->getManager();
    
            $product->setUser($this->getUser());
    
            $em->persist($product);
            $em->flush();
    
            return $this->redirectToRoute('some_route');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 openwrt双栈NAT
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用