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(),
    );
}
4

1 回答 1

1

我必须有一个听众或某处持续存在用户的东西。

我暂时解决这个问题的方法是:

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

直到我能找出是什么监听器或其他数据转换器导致了这种情况。

于 2013-02-15T19:21:36.663 回答