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 :)
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']]));
}
}
来源:https://stackoverflow.com/questions/15086287/assert-unique-validation-in-sonata-admin