Symfony表单价格字段 - 自定义断言与消息

时间:2016-02-18 22:04:55

标签: forms validation symfony

默认情况下,消息:此值无效。是不够的。我正在为我的实体中的每个属性添加@Assert以进行更具体的验证。

我在表单顶部全局显示错误 - 而不是单独显示 - 如果在本讨论的上下文中它是重要的。

/**
 * @ORM\Column(type="decimal", nullable=false, precision=10, scale=2)
 * @Assert\Type(message="list price must be a numeric value", type="decimal")
 * @Assert\NotBlank(message="list price cannot be empty")
 * @Assert\GreaterThanOrEqual(message="list price must be no less than zero", value = 0)
 */

private $listPrice;

这是我到目前为止所做的,但是当我输入一个值“D44.33”时表格仍然无效

如何覆盖默认的“类型”验证器?请注意其他验证器,如 GreaterThanOrEqual 按预期工作 - 但对于我的生活,我不能让“类型”工作???

2 个答案:

答案 0 :(得分:1)

类型decimal在Symfony中不是有效类型,因此它可能正在寻找自定义decimal类型并尝试转换数据并失败(这与类型一致)你得到的错误信息。)

允许类型列表如下:

http://symfony.com/doc/current/reference/constraints/Type.html#reference-constraint-type-type

请尝试使用此代码:

@Assert\Type(type="float", message="List price must be a numeric value")

答案 1 :(得分:1)

@Jason Roman - 再次感谢您的帮助

我遇到的问题是通过使用“invalid_message”解决的:

->add('listPrice', null, ['error_bubbling' => true, 'invalid_message' => '{{ value }} is not a valid list price'])