如何验证具有两个以上字段的实体为唯一实体 我知道Sonata管理员不直接支持默认的Symfony验证规则,而是通过其自己的内联验证(errorElement)。
请参阅:https://symfony.com/doc/3.x/bundles/SonataAdminBundle/reference/conditional_validation.html
我最终得到了自己的解决方案,但是效率不高,如果有人找到了更好的解决方案,那就太好了。
假设
` 使用Sonata \ CoreBundle \ Validator \ ErrorElement;
public function validate(ErrorElement $errorElement, $object)
{
$container = $this->getConfigurationPool()->getContainer();
$repo = $container->get('app.repository.article_translation');
$em = $this->modelManager->getEntityManager('App\ArticleBundle\Entity\ArticleTranslation');
$query = $em->createQueryBuilder('a')
->select('a')
->from('ArticleBundle:ArticleTranslation', 'a')
->andWhere('a.title = :title')
->andWhere('a.locale = :locale')
->setParameter('title', $this->getForm()->get('title')->getData())
->setParameter('locale', $this->request->getLocale());
if ($this->isCurrentRoute('edit')) {/* this will avoid checking the one which is being edited */
$query
->andWhere('ft.translatable != :id' )
->setParameter('id', $this->getSubject()->getId());
}
$article = $query
->getQuery()
->getOneOrNullResult();
if ($article) { // check if the article is already exist
$errorElement
->with('title')
->addViolation('This title is already exist')
->end()
;
}
}
结果: !https://imageshack.com/a/img921/3005/1Qkh0x.png
有何评论?
答案 0 :(得分:0)
您应在此处使用UniqueEntity Constraint。
在您的ArticleEntity中,只需添加:
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @UniqueEntity(
* fields={"title", "locale"},
* message="This title already exists."
* )
*/
并且您应该以更轻松的方式获得正确的错误消息。