Assert unique validation in Sonata Admin

筅森魡賤 提交于 2019-12-05 12:32:39

finally i defined a validation group for my entity:

use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
/*
 * @ORM\Table(name="default_doctor_specialty")
* @DoctrineAssert\UniqueEntity(fields="uniqueSlugName", message="A Speciality with same slug already exists", groups={"test"})
* @ORM\Entity
*/
class Test {
//..
/**
* @var string
* @Gedmo\Slug(fields={"name"},unique=false)
* 
* @ORM\Column(name="unique_slug_name", type="string", length=255, nullable=false , unique=true)
*/
private $uniqueSlugName;
}

and in admin class i used test validation group instead of default!

thanks to AHWEBDEV on github!

From this link

This is the full exemple , it depend on your symfony and sonata version.

// src/AppBundle/Entity/Service.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @UniqueEntity(
 *     fields={"host", "port"},
 *     errorPath="port",
 *     message="This port is already in use on that host."
 * )
 */
class Service
{
    /**
     * @ORM\ManyToOne(targetEntity="Host")
     */
    public $host;

    /**
     * @ORM\Column(type="integer")
     */
    public $port;
}

I prefer not to mess my entities with hundreds of lines of such low level details like validation. One can define validation rules inside the Admin class. Usually the validation rules are different for admins than for clients as well.

final class TestAdmin
{
    // … skipped for brevity

    public function validate(ErrorElement $errorElement, $object)
    {
        $errorElement->addConstraint(new UniqueEntity(['fields' => ['slug']]));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!