简体   繁体   中英

Don't persist existing datas in Symfony2

Is there a way to avoid persisting datas with Symfony2? Here is my example:

I have a user and a experience entity with one form. My experience entity is binded with user with cascade={persist} . So when a user fill his email address and his experience, both entities are created and binded.

My question is how to avoid to send user informations to the database if his email address already exists? Here is my function:

public function participeAction(Request $request)
{
    $type = new EcoActorsType();
    $form = $this->createForm($type);
    $form->handleRequest($request);

    if ($form->isValid())
    {
        $data = $form->getData();

        $doctrine = $this->getDoctrine();
        $em = $doctrine->getManager();

        $email = $data->getUserActor();
        $email = $email->getEmail();

        $is_email = $em
            ->getRepository('Mobility\PublicBundle\Entity\UserActor')
            ->findOneBy(array(
                'email' => $email
            ));

        if ($is_email == null)
        {
            $em->persist($data);
            $em->flush();
        }
        else
        {
            ????
        }

        $url = $this->generateUrl('public.frontpages.participe');
        return $this->redirect($url);
    }

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

Here is my data object:

object(Mobility\PublicBundle\Entity\EcoActors)[905]
    private 'id' => null
    private 'title' => string 'test experience' (length=15)
    private 'type' => int 0
    private 'start' => string 'test start' (length=10)
    private 'arrival' => string 'test arrival' (length=12)
    private 'description' => string 'test test test' (length=14)
    private 'game' => boolean false
    private 'useractor' => 
        object(Mobility\PublicBundle\Entity\UserActor)[898]
            private 'id' => null
            private 'email' => string 'test@test.fr' (length=12)
            private 'ges' => int 2
$existingUser = $em->getRepository( "you entity shortname AcmeBundle:Entity" )->findOneByEmail( $email );

if ( $existingUser !== null ) 
{
  //User exists
}else
{
  //User doesn't exist

}

On the database integrity side, you can use the @UniqueConstraint to have the schema assign the column as unique.

/**
 * @Entity
 * @Table(name="UserActor",uniqueConstraints={@UniqueConstraint(name="email_idx", columns={"email"})})
 */
class UserActor
{
    // ...
}

On the Controller side, you use the findOneBy helper functions with Doctrine (the default repository class will generate special find functions for each column in your Entity, such as findOneByEmail )

$user = $this->getDoctrine()
    ->getRepository('MobilityPublicBundle:UserActor')->findOneByEmail($email);
if ($user) {
    // User exists
} else {
    // User doesn't exist
}

Finally it was simple. I just setted the object with the one which was already in the data base. Here is the new code:

public function participeAction(Request $request)
{
    $type = new EcoActorsType();
    $form = $this->createForm($type);
    $form->handleRequest($request);

if ($form->isValid())
{
    $data = $form->getData();

    $doctrine = $this->getDoctrine();
    $em = $doctrine->getManager();

    $email = $data->getUserActor();
    $email = $email->getEmail();

    $is_email = $em
        ->getRepository('Mobility\PublicBundle\Entity\UserActor')
        ->findOneBy(array(
            'email' => $email
        ));

    if ($is_email == null)
    {
        $em->persist($data);
        $em->flush();
    }
    else
    {
        $data->setUseractor($is_email);
        $em->persist($data);
        $em->flush();
    }

    $url = $this->generateUrl('public.frontpages.participe');
    return $this->redirect($url);
}

return array(
    'form' => $form->createView()
);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM