简体   繁体   中英

Symfony3 - @UniqueEntity is not working

I can´t find the way to handle the database error when I intend to save data @uniqueConstrainst of my database allow. The problem is that my @UniqueEntity don´t handle the error before the database error displays.

This is my code

    * @ORM\Table(name="persona_idioma", uniqueConstraints={@UniqueConstraint(name="persona_idioma_unique",columns={"id_persona","id_idioma"})},indexes={@ORM\Index(name="IX_Relationship11", columns={"id_idioma"}), @ORM\Index(name="IX_Relationship12", columns={"id_persona"})})
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PersonaIdiomaRepository")
 * @UniqueEntity(
 *     fields={"idPersona", "idIdioma"},
 *     errorPath = "idPersona", 
 *     message="mensaje"
 *       
 * )

Updated: I have just added the columns of the entity

/**
     * @var \AppBundle\Entity\Persona
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Persona",inversedBy="idiomas")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_persona", referencedColumnName="id_persona")
     * })
     */
    private $idPersona;

    /**
     * @var \AppBundle\Entity\Idioma
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Idioma")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_idioma", referencedColumnName="id_idioma")
     * })
     */
    private $idIdioma;

And the controller where the entity is persisted

$formulario->handleRequest($request);

    if ($formulario->isSubmitted() && $formulario->isValid()) {
        $em->persist($persona);
        $em->flush();
        return $this->redirectToRoute('persona_edit', array('id_persona' => $persona->getIdPersona()));
    }

    return $this->render('persona/new_edit.html.twig', [
                'formulario' => $formulario->createView(),
    ]);

I had the same problem as u, I changed my code from:

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @UniqueEntity(fields={"username", "email"}, message="This value is already taken")
 */

to:

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @UniqueEntity(fields={"username"}, message="This username is already taken")
 * @UniqueEntity(fields={"email"}, message="This email is already taken")
 */

It's strange but it worked for me. Just give me sign if I helped u.

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