Symfony2, Doctrine, @UniqueEntity handle exception

后端 未结 2 2009
时光说笑
时光说笑 2021-01-23 23:40

ENTITY

use Doctrine\\ORM\\Mapping as ORM;
use Symfony\\Component\\Validator\\Constraints as Assert;
use Symfony\\Bridge\\Doctrine\\Validator\\Co         


        
相关标签:
2条回答
  • 2021-01-24 00:14

    trouble was in form Type class, to work this unique-combination you have to add all values to fields you want to be unique, on my example will be

      $builder
                ->add('accountID', 'hidden', array ('data' => $options['acountID']))
                ->add('keyID', 'text')
                ->add('vCode', 'text');
    

    i added hidden field (accontID) and fill it with data and then i got proper error to form-errors, if you will not fill there will be null values (so i don't know why it will NOT check uniques)

    that is solution for me but basicly @Sybio help meto understand a lot of so i will check his answer as answer ^_^

    0 讨论(0)
  • 2021-01-24 00:21

    Duplicate entry '38-1233-123' for key 'accountID'

    If you want to check the uniqueness of accountId alone, add this to your class:

    @UniqueEntity(fields={"accountID"}, message="This account is already taken")
    

    Here the full code that check the uniqueness of the combinaison "keyID", "vCode", "accountID" and also the uniqueness of "accountID" alone:

    <?php
    
    // ...
    
    /**
     * @ORM\Table(name="_apiKey")
     * @ORM\Entity(repositoryClass="Eve\ProfileBundle\Entity\Repository\apiKeyRepository")
     * @UniqueEntity(fields={"keyID", "vCode", "accountID"}, message="you already own this api")
     * @UniqueEntity(fields={"accountID"}, message="This account ID is already taken")
     */
    class apiKey
    {
    

    I don't know if you saw that the error only affect the field accountID, if you don't want this behavior just remove "unique=true" from your property $accountID.

    If you just want to say that the cominaison "keyID", "vCode", "accountID" must be unique in the database, proceed like that:

    /**
     * @ORM\Table(name="_apiKey",
     *      uniqueConstraints = {
     *          @ORM\UniqueConstraint(name="_api_key_key_id_v_code_account_id", columns={"keyID", "vCode", "accountID})
     *      }
     * )
     *
     * ...
     * etc, ...
     */
    class apiKey
    
    0 讨论(0)
提交回复
热议问题