我有以下情况:
在我的 FormType 类中:
...
$builder->add('fieldToValidate', 'number', array('required' => false))
...
在模型类中:
...
use Symfony\Component\Validator\Constraints as Assert;
...
/**
* @var float $fieldToValidate
*
* @ORM\Column(name="fieldToValidate", type="float", nullable=true)
* @Assert\Type(type="float", message="Must be a number.")
*/
private $fieldToValidate;
在 Controller 的 Action 中:
$entity = $this->getService('my_service')->findMyEntity($entityId);
$editForm = $this->createForm(new MyEntityType(), $entity, $myOptions);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()){
当我在 fieldToValidate(例如“foo”)中提交带有一些无效数据的表单时,出现异常:
Expected argument of type "numeric", "boolean" given
在 Controller 中调试我的代码我注意到它引发了异常$editForm->bindRequest($request);
我如何才能使用 $editForm->isValid()
来控制异常。不是为此我在模型和形式中验证吗?
最佳答案
/**
* @Assert\Regex(pattern="/\d+/")
*/
关于forms - 验证 symfony2 中的数字字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10914193/