2013-02-13 71 views
3

我遇到了一個問題,即使表單無效,我仍然有一個表單類型可以保留關聯的實體。 我已經確認窗體確實有錯誤,通過$ form-> getErrorsAsString()。我也已經證實,檢查表單是否有效的邏輯if語句是錯誤的。儘管事實上這個表單從來都是無效的,但實體仍然存在。即使表格有錯誤,實體仍然存在

我不確定我在做什麼錯在這裏,因爲我沒有其他地方可以找到要麼堅持實體或刷新實體經理。這裏是我的控制器:

/** 
* @Route("/settings/profile", name="settings_profile") 
* @Template(); 
*/ 
public function profileAction() 
{ 
    $user = $this->getUser(); 
    $profile = $user->getUserProfile(); 

    if (null === $profile) { 
     $profile = new UserProfile(); 
     $profile->setUser($user); 
     $profileDataModel = $profile; 
    } else { 
     $profileDataModel = $this->getDoctrine()->getManager()->find('MyAppBundle:UserProfile',$profile->getId()); 
    } 

    $form = $this->createForm(new ProfileType(),$profileDataModel); 
    $request = $this->getRequest(); 

    if ($request->getMethod() === 'POST') { 
     $form->bind($request); 

     if ($form->isValid()) { 
      // This logic never gets executed! 
      $em = $this->getDoctrine()->getManager(); 
      $profile = $form->getData(); 
      $em->persist($profile); 
      $em->flush(); 
      $this->get('session')->setFlash('profile_saved', 'Your profile was saved.'); 
      return $this->redirect($this->generateUrl('settings_profile')); 
     } 
    } 

    return array(
     'form'  => $form->createView(), 
    ); 
} 
+0

'$ em-> persist($ profile); $ em-> flush();'可以對持久化對象進行響應,所以你的代碼不能跳過''isValid()'控制。你可以使用記錄器來確定你所聲稱的是什麼 – DonCallisto 2013-02-13 08:03:27

+1

你的表格只是有效的。也許你必須定義驗證約束。 – 2013-02-13 08:09:22

+0

你是說因爲你的表格在第一次提交後被預先填好? – Pierrickouw 2013-02-13 08:33:56

回答

1

我必須有一個監聽器或某個地方持久用戶。

我的工作圍繞這個暫時是做:

$em = $this->getDoctrine()->getManager() 
if ($form->isValid()) { 
    // persist 
} else { 
    $em->clear(); 
} 

,直到我能揪出什麼監聽器或其他數據轉換是導致此。

+1

或者做$ em-> refresh($ profile);這將重新加載原始數據。 – Cerad 2013-02-15 21:09:45

+1

並將您自己的偵聽器掛在實體管理器上並抓取preFlush事件。這將驗證flush是否真的被調用。 – Cerad 2013-02-15 21:11:28

相關問題