【问题标题】:Symfony3.4 Sonata Admin multi language site, Entity validation with more than 2 fields as uniqueSymfony3.4 Sonata Admin 多语言站点,具有超过 2 个字段的实体验证作为唯一
【发布时间】:2018-07-12 10:16:02
【问题描述】:

如何验证具有超过 2 个字段的实体是唯一的 我知道奏鸣曲管理员不直接支持默认的 Symfony 验证规则,而是通过它自己的内联验证(errorElement)。

见:https://symfony.com/doc/3.x/bundles/SonataAdminBundle/reference/conditional_validation.html

我最终得到了自己的解决方案,但效率不高,如果有人找到更好的解决方案,那就太好了。

假设

  1. 实体是 ArticleTranslation
  2. 存储库被声明为服务
  3. 多语言网站
  4. 标题、语言环境是唯一的

` 使用 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?

【问题讨论】:

    标签: validation symfony-3.4


    【解决方案1】:

    你应该在这里使用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."
     * )
     */
    

    并且您应该以比您所做的更轻松的方式获得正确的错误消息。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多