dongxieyi9115 2013-05-11 09:45
浏览 33
已采纳

特征上的Symfony2回调验证

I want to use callback validation on a trait. For example:

<?php
namespace Vendor\Bundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;

/**
 * @Assert\Callback(methods={"validateReview"}, groups={"review"})
 */
trait ReviewableEntity
{
    //...

    /**
     * @param ExecutionContext $context
     */
    public function validateReview(ExecutionContext $context)
    {

        //...

        $context->addViolationAt('review', 'Review must be valid', [], null);

        //...

    }

    //...

}

But it doesn't seem to work. Anyone know if this is this even possible?

  • 写回答

2条回答 默认 最新

  • dongwen9975 2014-11-03 21:09
    关注

    If the annotation is on the trait (and not on the method, which is possible with Symfony 2.4+), the callback validator cannot be used with annotations in a trait.

    You must use this method if your version of Symfony2 is older than 2.4:

    namespace Vendor\Bundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\Validator\ExecutionContext;
    use Symfony\Component\Validator\Mapping\ClassMetadata;
    
    trait ReviewableEntity
    {
        //...
    
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addConstraint(
                new Assert\Callback(
                    'validateReview',
                    array(
                        'groups' => array('review'),
                    )
                )
            );
        }
    
        /**
         * @param ExecutionContext $context
         */
        public function validateReview(ExecutionContext $context)
        {
    
            //...
    
            $context->addViolationAt('review', 'Review must be valid', [], null);
    
            //...
    
        }
    
        //...
    
    }
    

    This is just the normal php way to deal with validators without using annotations or configuration file in XML or YML.

    I've found this answer with this google query "github symfony entity trait assert callback" as I was fighting with the same problem. For me the first result was this gihtub page containing code that solve the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?