1

我有以下问题:

我想在将对象保存到数据库之前检查一些东西:

这是我的控制器:

/**
 * Edits an existing Document entity.
 *
 * @Route("/{id}", name="document_update")
 * @Method("PUT")
 * @Template("ControlBundle:Document:edit.html.twig")
 */
 public function updateAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();    
        $entity = $em->getRepository('ControlBundle:Document')->find($id);

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

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new DocumentType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
           $document = $em->getRepository('ControlBundle:Document')->findOneBy(array(
            'id' => $id,
            ));

           if ($document->getCount() > 100)
              $em->flush();
        }

      return array(
        'entity' => $entity,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
     );
  }

在我的数据库中,我有:

id   count .......
23    110  

在我的表格中我编辑:

id   count .......
23    34  

但是当我这样做时:

$document = $em->getRepository('ControlBundle:Document')->findOneBy(array(
   'id' => $id,
));

//here $document->getCount() return 34; ------WHY? should return 110!!!
if ($document->getCount() > 100)
   $em->flush();

最好的问候:D

4

1 回答 1

2

Doctrine Entity Manager已经在管理这个实体(ID=23 的文档),它不会第二次从数据库中重新加载数据,它只是使用它已经管理的实体,其数值已被表格中的 34 替换...

尝试这个 :

 /**
  * Edits an existing Document entity.
  *
  * @Route("/{id}", name="document_update")
  * @Method("PUT")
  * @Template("ControlBundle:Document:edit.html.twig")
  */
 public function updateAction(Request $request, $id) {
    $em = $this->getDoctrine()->getManager();    
    $entity = $em->getRepository('ControlBundle:Document')->find($id);

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

    $lastCountValue = $entity->getCount();

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createForm(new DocumentType(), $entity);
    $editForm->bind($request);

    if ($editForm->isValid() && lastCountValue > 100) {
        $em->flush();
    }

  return array(
    'entity' => $entity,
    'edit_form' => $editForm->createView(),
    'delete_form' => $deleteForm->createView(),
 );

}

于 2013-04-25T06:26:58.493 回答