Assert unique validation in Sonata Admin

扶醉桌前 提交于 2019-12-07 10:12:43

问题


I'm using Symfony 2.1 for a project. I use SonataAdminBundle for administration usage. i want to add an assert to my slug property in my admin class.. how can i do this?

in my entity i had set the assertion but it seems that it doesn't work here :(

related codes: the entity :

/*
 * @ORM\Table(name="default_doctor_specialty")
 * @UniqueEntity("uniqueSlugName")
 * @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;
}

in admin class:

class TestAdmin extends Admin {

protected $formOptions = array(
    'validation_groups' => 'Default'
);
 //...
  }

why the default validation doesn't work???

& even if doesn't work like this how can i set the unique validation inside admin class ???

thanks for your answers :)


回答1:


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!




回答2:


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;
}



回答3:


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']]));
    }
}


来源:https://stackoverflow.com/questions/15086287/assert-unique-validation-in-sonata-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!