0

I need the Symfony2 Validator to return an array rather than an object.

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.

I'm not using the in-built forms, just the raw Validator.

4

2 回答 2

4

您可以遍历对象以创建错误数组。

$errors = $this->get('validator')->validate( $insert );

$errorArray = array();

foreach($errors as $error)
{
    $errorArray[$error->getPropertyPath()] = $error->getMessage();
}
于 2013-07-07T21:37:41.407 回答
1

Validator->validate()返回一个ConstraintViolationListInterface实现IteratorAggregate接口的对象。对其进行简单的 foreach 并从对象中构造所需的数组ConstraintViolationInterface

于 2013-07-07T19:18:37.917 回答