shuba.ivan
shuba.ivan

Reputation: 4061

Symfony Doctrine UniqueEntity repositoryMethod

I have entity Users and three unique fields and use for this @UniqueEntity, but I don't know how in message visible exactly fields already in DB ? I think maybe like Assert annotation

 * @Assert\Type(
 *     type="array",
 *     message="The value {{ value }} is not a valid {{ type }}."
 * )

but not work

my entity:

/**
* Users.
*
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="Artel\ProfileBundle\Entity\UsersRepository")
* @ExclusionPolicy("all")
* @UniqueEntity(
*     fields={"email", "telephone", "skype"},
*     errorPath="entity",
*     message="This email, telephone or skype is already."
* )
*/
class Users implements UserInterface
{
use Timestampable;
    /**
 * @var string
 *
 * @ORM\Column(name="email", type="string", length=255,  unique=true, nullable=true)
 * @Expose()
 * @Assert\Length(min=3, max=255)
 * @Assert\NotBlank()
 * @Assert\Email()
 */
protected $email;

/**
 * @var string
 *
 * @ORM\Column(name="skype", type="string", length=255, unique=true, nullable=true)
 * @Assert\Length(min=3, max=255)
 * @Expose()
 */
protected $skype;

/**
 * @var string
 *
 * @ORM\Column(name="telephone", type="string", length=255, unique=true, nullable=true)
 * @Assert\Length(min=3, max=255)
 * @Expose()
 */
protected $telephone;

Upvotes: 1

Views: 802

Answers (1)

Matteo
Matteo

Reputation: 39390

You have configure the constraint with the unique of the tuple: combination value of the field email telephone and skype is unique.

From the doc:

This required option is the field (or list of fields) on which this entity should be unique. For example, if you specified both the email and name field in a single UniqueEntity constraint, then it would enforce that the combination value is unique (e.g. two users could have the same email, as long as they don't have the same name also).

If you need to require two fields to be individually unique (e.g. a unique email and a unique username), you use two UniqueEntity entries, each with a single field.

So you need to specify three different unique constraint, as example:

/**
* Users.
*
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="Artel\ProfileBundle\Entity\UsersRepository")
* @ExclusionPolicy("all")
* @UniqueEntity(
*     fields="email",
*     errorPath="entity",
*     message="This email is already in use."
* @UniqueEntity(
*     fields="telephone",
*     errorPath="entity",
*     message="This telephone is already in use."
* @UniqueEntity(
*     fields="skype",
*     errorPath="entity",
*     message="This skype account is already in use."
* )
*/
class Users implements UserInterface

Hope this help

Upvotes: 2

Related Questions