gremo
gremo

Reputation: 48487

Symfony2 UniqueEntity validation constraint as concatenation?

In my Tag entity i need to avoid creating a tag with the same name along all tags created by a given user. There is a many-to-one relation with User entity, named user.

I'm enforcing this constraint either in database (using uniqueConstraints) and in form validation with UniqueEntity. But i can't understand this sentence in Symfony2 documentation about this constraint:

This required option is the field (or list of fields) on which this entity should be unique. For example, you could specify that both the email and name fields in the User example above should be unique.

But i need that name and user are unique as a whole. Is this possible and how? Here is an example of not working one: both name and user are checked for uniqueness as singular fields.

/**
 * @ORM\Entity(repositoryClass="Acme\HelloBundle\Repository\TagRepository")
 * @ORM\Table(
 *     name="tag",
 *     uniqueConstraints={
 *         @ORM\UniqueConstraint(columns={"name", "user_id"}),
 *     })
 * @UniqueEntity(fields={"name", "user"})
 */
class Tag implements TenantableEntityInterface
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=31)
     * @Assert\NotBlank
     * @Assert\MaxLength(limit="31")
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="tags")
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

}

EDIT: with the definition above the form validates but i get the:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'name-1' for key 'UNIQ_389B7835E237E06A76ED395'.

Creating two tags with the same name and the same user.

Upvotes: 1

Views: 3538

Answers (2)

nvvetal
nvvetal

Reputation: 1793

Just note:

For yaml use:

constraints:
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
        fields: username
        groups: [SomeYourGroup]

Or for annotation: use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

  • @UniqueEntity(fields={"username"}, groups={"SomeYourGroup"})

In documentation http://symfony.com/doc/current/reference/constraints/UniqueEntity.html

groups not available!!!

Upvotes: 1

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44851

If you want the combination of both name and user be unique, then use:

@UniqueEntity(fields={"name", "user"})

If you want them be unique separately, use this:

@UniqueEntity(fields="name")
@UniqueEntity(fields="user")

The same applies for unique constraints on the table.

Upvotes: 3

Related Questions