【发布时间】:2016-10-09 12:01:19
【问题描述】:
我有案例,也有附件。这被编码为具有 OneToMany 关联到 Attachment 实体的 Case 实体。 Attachment 实体具有与 Case 实体的 ManyToOne 关联。代码:
class Case {
/**
* @var integer
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Attachment", mappedBy="case",cascade={"persist"})
*/
protected $attachments;
class Attachment
{
/**
* @var integer
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Case", inversedBy="attachments")
* @ORM\JoinColumn(name="case_id", referencedColumnName="id")
*/
protected $case;
}
我正在尝试以下方法。我假装将整个案例显示/打开到一个页面中。在页面内部,会有附件列表。在该列表的末尾,我假装放置了一个用于提交新附件的表单。
所以我写了一个控制器来展示这个案例,我创建了一个新的附件表单(AttachmentType)并将它放在树枝模板的中间,将它作为参数传递给操作的渲染调用。
// CaseController.php
/**
* @Route("/cases/show/{case}", name="showCase", requirements={ "case" : "\d+" } )
*/
public function showCaseAction(Request $request, $case)
{
$theCase = $this->getDoctrine()->getRepository('AppBundle:Case')->findOneById( $case );
$attachment = new Attachment();
$attachment->setCase( $theCase );
$attachmentForm = $this->createForm(AttachmentType::class, $attachment);
if ( ! $theCase ) {
$this->addFlash('danger', $this->get('translator')->trans('cases.show.case_not_found', [ '%case%' => $case ] ) );
}
return $this->render('cases/caseContainer.html.twig', array( 'case' => $theCase, 'attachmentform' => $attachmentForm->createView() ) );
}
我还在控制器中写入了一个 newAttachmentAction 来执行附件创建。
我不再在这里写代码了。我不想限制可能的答案。
我的问题是,当调用 newAttachmentAction 时,我无法弄清楚如何恢复 Case 对象,所以我可以进行关联。我不知道是否应该在附件表单生成器中放置一些东西(HiddenType、EntityType 等)来存储 Case 对象,或者使用其他一些 Symfony 机制(服务、关闭、存储令牌)可能会更好。我在网上进行了广泛的搜索,但我读了很多文章,我被卡住了!我可能错过了正确的搜索关键字。
我希望我已经说清楚了,因此有人可以为我指明正确的方向以找到示例或教程。
最好的问候,非常感谢您的时间和关注!
【问题讨论】:
-
您好,我又一直在寻找。我发现了一些有助于实现目标的东西:DataTransformers。但我对这个解决方案不满意。要将隐藏字段包含到包含 Case 对象的 ID 值的表单中,以便我可以在接收回表单时检索 Case 对象,但可以通过现代浏览器调试工具轻松更改 HTML 表单字段值。我正在考虑一种服务器端关联,比如说,CSFR 令牌和 Case 对象。对这种方式有什么建议吗?
标签: symfony model-associations