【发布时间】:2018-07-12 10:16:02
【问题描述】:
如何验证具有超过 2 个字段的实体是唯一的 我知道奏鸣曲管理员不直接支持默认的 Symfony 验证规则,而是通过它自己的内联验证(errorElement)。
见:https://symfony.com/doc/3.x/bundles/SonataAdminBundle/reference/conditional_validation.html
我最终得到了自己的解决方案,但效率不高,如果有人找到更好的解决方案,那就太好了。
假设
- 实体是 ArticleTranslation
- 存储库被声明为服务
- 多语言网站
- 标题、语言环境是唯一的
` 使用 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
任何cmets?
【问题讨论】: