2013-04-25 100 views
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

+0

首先,你從請求綁定'$ document',然後你從數據庫中尚未持久值覆蓋它。而且它還沒有持續下去,因爲你現在沒有沖洗它。我不明白你爲什麼要覆蓋'$ document',你應該刪除這行'$ document = $ em-> getRepository('ControlBundle:Document') - > findOneBy(array('id'=> $ id,) );'然後應該工作。 – timaschew 2013-04-25 07:04:44

回答

2

主義實體管理器已經管理這個實體(文檔與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(), 
); 

}

+0

謝謝你我的朋友!那就對了! – rpayanm 2013-04-25 16:00:00