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.

/**
 * @ORMEntity(repositoryClass="AcmeHelloBundleRepositoryTagRepository")
 * @ORMTable(
 *     name="tag",
 *     uniqueConstraints={
 *         @ORMUniqueConstraint(columns={"name", "user_id"}),
 *     })
 * @UniqueEntity(fields={"name", "user"})
 */
class Tag implements TenantableEntityInterface
{

    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=31)
     * @AssertNotBlank
     * @AssertMaxLength(limit="31")
     */
    private $name;

    /**
     * @ORMManyToOne(targetEntity="User", inversedBy="tags")
     * @ORMJoinColumn(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.


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.


Just note:

For yaml use:

constraints:
    - SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity:
        fields: username
        groups: [SomeYourGroup]

Or for annotation: use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;

  • @UniqueEntity(fields={"username"}, groups={"SomeYourGroup"})
  • In documentation http://symfony.com/doc/current/reference/constraints/UniqueEntity.html

    groups not available!!!

    链接地址: http://www.djcxy.com/p/57878.html

    上一篇: 如何为symfony2中的未绑定表单字段添加验证

    下一篇: Symfony2 UniqueEntity验证约束作为级联?