[英]Symfony 2 Validator - how to return an array
I need the Symfony2 Validator to return an array rather than an object. 我需要Symfony2验证程序返回一个数组而不是一个对象。
So something like this: 所以像这样:
$insert = new MyEntity();
$insert->setTest1( 'testtesttest' );
$validator = $this->get('validator');
$errors = $validator->validate($insert);
...would enable this: ...将启用此功能:
$errors[0]['message'] = "The email is not valid"
Just a simple array as parsing the object returned is very difficult. 仅仅一个简单的数组来解析返回的对象是非常困难的。
I understand the validator config, but I just need the Validator to return an array not its usual object. 我了解验证器配置,但我只需要验证器即可返回数组而不是其通常的对象。
I'm JSON encoding the result and (a) json_encode struggles with objects + (b) I don't want to return the whole object just a list of errors. 我正在对结果进行JSON编码,并且(a)json_encode与对象作斗争+(b)我不想仅将错误列表返回整个对象。
I'm not using the in-built forms, just the raw Validator. 我使用的不是内置表单,而是原始的Validator。
You can loop over the objects to create an array of errors. 您可以遍历对象以创建错误数组。
$errors = $this->get('validator')->validate( $insert );
$errorArray = array();
foreach($errors as $error)
{
$errorArray[$error->getPropertyPath()] = $error->getMessage();
}
Validator->validate()
returns a object of ConstraintViolationListInterface
, which implements the IteratorAggregate
interface. Validator->validate()
返回ConstraintViolationListInterface
对象,该对象实现IteratorAggregate
接口。 Simple foreach over it and construct your desired array out of the ConstraintViolationInterface
objects. 对其进行简单的foreach并从ConstraintViolationInterface
对象中构造所需的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.