1

controller portion:

        $contact->setEmail($request->request->get('email'))
                ->setFirstName($request->request->get('firstname'))
                ->setLastName($request->request->get('lastname'))
                ->setSource($request->request->get('source'))
                ->setIpAddress($request->request->get('ipaddr'))
                ->setCreated(new \DateTime());

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

        $response = new Response(json_encode(
          array(
            'errors'=>$this->errors
          )
        ));
        return $response;

validation.yml:

Mailer\MainBundle\Entity\Contact:
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: email
    properties:
        email:
            - Email:
                message: The email you entered is invalid
                checkMX: false
        ipAddress:
            - Ip: ~
        source:
            - Length:
                min: 2
                max: 50
                minMessage: Must be between 2 and 50 characters
                maxMessage: Must be between 2 and 50 characters

$this->errors always comes out as an empty object regardless of what is in input. validation for this same entity works in other controllers, but I am validating via the $form->isValid() method for those. This controller is for API functionality - so I cannot use that method. Any help is much appreciated :)

1 Answer 1

3

I had a similar issue. The problem is not with the validator. The problem is caused because json_encode doesn't handle certain objects nicely. In this case, if you create a string or simple array of all the errors, and then return the string/array as json, it should work.

$messages = array();
foreach($this->errors as $error){
    $messages[] = $error->getMessage();
}
$response = new Response(json_encode(
      array(
        'errors'=>$messages
      )
));
return $response;

OR

$messages = '';
foreach($this->errors as $error){
    $messages .= $error->getMessage() . ";";
}
$response = new Response(json_encode(
      array(
        'errors'=>$messages
      )
));
return $response;

This is what solved my problem with json_encode. hope it will work for you too.

EDIT: It looks like the validator returns a resource. json_encode cannot encode resources. see php docs

Sign up to request clarification or add additional context in comments.

Comments

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.