Symfony验证回调 - 如何在错误时获取属性名称?

3
我已经设置了实体的生命周期回调,以模拟来自MySQL的ENUM字段进行验证。它运行良好,但当出现错误时,它不提供属性名称,因此与Assert返回的错误格式不匹配。在下面的示例中,第一个错误来自回调,没有有关属性的信息,而其余错误是由Assert生成的,并包括相关属性:UsedBundle \ AdController。
$errors = $this->form_errors->getErrorMessages($form);
        \Doctrine\Common\Util\Debug::dump($errors);

数组(3) { [0]=> 字符串(14) "无效的门!" ["powerHp"]=> 数组(1) { [0]=> 字符串(32) "该值应为50或更多。" } ["price"]=> 数组(1) { [0]=> 字符串(34) "该值应为1000或更多。" } }

由于该消息,我可以知道错误来自哪里,但这也会使生成用于向用户输出错误变量的函数出错。

设置如下:

UsedBundle\Entity\Ad

namespace UsedBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
 * @ORM\Entity(repositoryClass="UsedBundle\Repository\AdRepository")
 * @ORM\HasLifecycleCallbacks 
 * @ORM\Table(name="ads")
 */
class Ad
{

/**
 * @var integer
 *
 * @ORM\Id
 * @ORM\Column(type="smallint",length=4,unique=true,options={"unsigned":true})
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

......

public static $valid_doors = array(
    '2' => '2',
    '3' => '3',
    '4' => '4',
    '5' => '5',
);

/**
 * @Assert\Callback
 */
public function validate(ExecutionContextInterface $context, $payload)
{
    if (!in_array($this->getdoors(), self::$valid_doors)) {
        $context->buildViolation('Invalid doors!')
            ->atPath('doors')
            ->addViolation();
    }
}
}
1个回答

1
在您的情况下(当然,如果您的Symfony版本不早于2.4),我建议使用静态验证函数。当您使用静态函数时,必须传递$object!
/**
 * @static validate
 *
 * @param $object 
 * @param ExecutionContextInterface $context
 */
public static function validate($object, ExecutionContextInterface $context)
{
    if (!in_array($object->getdoors(), self::$valid_doors)) {
        $context->buildViolation('Invalid doors!')
            ->atPath('doors')
            ->addViolation();
    }
}

正如您所看到的- 没有注释/** @Assert\Callback */!此外,不必编写类注释@ORM\HasLifecycleCallbacks。希望这有所帮助!

另外 - 这是指向官方Symfony文档的链接


感谢@staskrak。我没能让它工作起来。不确定如何传递$ object参数。可能是这个原因。顺便说一下,我正在使用3.2版本。我知道有相关的文档,但它们并没有解决属性名称的问题。 - BernardA
@BernardA ->atPath('doors') - 这是一个属性,错误将与此相关。 如果您有嵌入式表单->则必须在注释中使用Assert\Valid()。 - staskrak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接