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.

AndroidLearner
  • 4,500
  • 4
  • 31
  • 62
Rodrigo Puente
  • 101
  • 3
  • 13

1 Answers1

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.

Community
  • 1
  • 1
BADAOUI Mohamed
  • 2,146
  • 1
  • 17
  • 14
  • 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. – Rodrigo Puente Dec 28 '12 at 17:40