在 Doctrine Flush 之前添加值

Add values before Doctrine Flush

我想在冲洗前添加值。 我的其他值来自与我的实体映射的表单,因此当我尝试使用 setData() 时,我的字段停留在 "null".

代码:

    public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('BlogBlogBundle:Blog')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Blog entity.');
    }

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {
        $editForm->get('date')->setData(date("Y-m-d"));
        $usr= $this->get('security.context')->getToken()->getUser();
        $usr->getUsername();
        $editForm->get('author')->setData($usr);
        var_dump($editForm);
        $em->flush();

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

    return $this->render('BlogBlogBundle:Admin:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

不需要上使用getDatasetData表格, 您应该使用实体本身的 setter 。 您将 save/persist 不是形式,而是实体。 该表单还在实体 class 上使用 setter 来发送数据。

喜欢:

public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('BlogBlogBundle:Blog')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Blog entity.');
    }

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {
        $usr = $this->get('security.context')->getToken()->getUser();
        //don't know what you wanna do with the username
        $usr->getUsername();
        //use the setter for the date... maybe $entity->setCreatedAt()
        $entity->setDate(date("Y-m-d"));
        //also use the setter for the user on the entity
        $entity->setAuthor($usr);
        var_dump($entity);
        $em->flush();

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

    return $this->render('BlogBlogBundle:Admin:edit.html.twig', array(
        'entity' => $entity,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

您必须更改映射到表单的实体并使用正确的实体字段设置器(我试过猜测)。尝试修改:

 ...
 if ($editForm->isSubmitted() && $editForm->isValid()) {
        $entity->setDate(date("Y-m-d"));
        $usr= $this->get('security.context')->getToken()->getUser();
        $usr->getUsername();
        $entity->setAuthor($usr);
        $em->persist($entity);
        $em->flush();
        ...
    }