0

I'm using Symfony2 along with doctrine2.

I need to know if a username exist on a table, so I'm calling this method by AJAX...

public function existeUsername()
{
    $req = $this->getRequest();
    $user = $req->request->get('user');
    $em = $this->getDoctrine()->getEntityManager();
    $usuario = $em->getRepository('RECURSIVAUserBundle:Usuario')->findOneByUsername($user);
    if ($usuario): 
        //user found
        $response = new Response(json_encode(array('error' => true, 'usuario' => $usuario, 'user' => $user)));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    else: 
        //did not found the user
        $response = new Response(json_encode(array('error' => false, 'user' => $user)));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    endif;
}

The method works as expected returning true if the username exists in the database or false if not. But when returning the user data from an existing user ($usuario), it always return an empty JSON array ({}) and not the expected object. Any ideas?

If I var_dump($usuario) before returning the response it prints out all the correct fields and values for that username.

1 Answer 1

0

Indeed, all properties of your user are private. Yet json_encode, encode only public object properties.

You can so implement JsonSerializable. see more details here or set these properties to public (worse solution)

Hope this helps.

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

1 Comment

If I try to access a property of the returned object (i.e: var_dump($usuario->username)) it shows an error saying I can't access a private property of that object. Maybe then, that's why it sends an empty array. I console.dir the returning JSON from the AJAX call, it always prints out {} for $usuario.

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.