symfony symfony3新单个ManyToOne对象(拥有关联方)

时间:2016-10-09 12:01:20

标签: symfony model-associations

我有案例,也有附件。这被编码为Case实体,OneToMany与Attachment实体关联。 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)并将其放在twig模板的中间,将其作为参数传递给action的render调用。 / p>

// 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等)放入Attachment Form Builder来存储Case对象,或者可能更好地使用其他一些Symfony机制(Services,Closure,StorageTokens)。我已经在网上进行了广泛的搜索,但我读了很多文章,我被困了!我可能错过了正确的搜索关键字。

我希望自己能够清醒自己,因此有人可以指出我找到一个示例或教程的正确方向。

致以最诚挚的问候,非常感谢您的时间和关注!

1 个答案:

答案 0 :(得分:0)

为了创建一个Case,我将在CaseformType中为附件属性添加一个HiddenType。

将data_class设置为Attachment

当您创建表单时,您将使用附件引用传递Case的新实例。

发布后,当您收到表单数据时,您将拥有链接对象