Object persists even when the form has an error

I have a problem where I have a form type that persists in a bound object even if the form is not valid. I have confirmed that the form does indeed have errors via $ form-> getErrorsAsString (). I also confirmed that a boolean if statement that checks if a form is valid or not is wrong. The essence still persists, even though the form is never valid.

I'm not sure what I am doing wrong here, as I have no other place I can find, either by saving the object or erasing the object manager. Here's my controller:

/**
 * @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(),
    );
}

      

+3


source to share


1 answer


I must have a listener or something somewhere where the user is saved.

My job for this is temporarily:



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

      

Until I can find out what is calling this listener or other data transformer.

+1


source







All Articles