Search code examples
symfonysonata-admin

Check whether a newly created object is unique by several fields


I have to check a submitted form against the existing database to make sure it is not duplicated by the combination of several fields, say supplier_id, invoice_no and amount.

Is there a built-in method or should I write a code myself? If so - what are guidelines: where to put it, what are the good practices?

At the moment I am extending the CRUD controller and overwriting the createAction adding the condition there. Not sure whether this method is a good practice.


Solution

  • Example:

    <?php
    
    namespace AppBundle\Entity\User;
    
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    
    /**
     * @ORM\Entity
     * @UniqueEntity({"name", "email"}, message="This value is in a database.")
     */
    class User
    {
    
        /**
         * @var string
         */
        protected $name;
    
        /*
         * @var string
         */
        protected $email;
        ...
    }