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.

2 Answers 2

5

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Validator->validate() returns a object of ConstraintViolationListInterface, which implements the IteratorAggregate interface. Simple foreach over it and construct your desired array out of the ConstraintViolationInterface objects.

2 Comments

You can't foreach over it as it is an object with only private properties
False. Have you read my answer? validate() returns a traversable list, over which you can iterate with foreach and the foreach should return objects of ConstraintViolationInterface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.