1

I use this code for getting all users in the database

$users= $this->getDoctrine()
        ->getRepository('AppBundle:Users')
        ->findAll();
        return $this->render('livre/users.html.twig',array(
            'users' => $users,
        ));

But me I want get only some fields sush as name,email and hide fields like password.. Thanks.

user3057822
  • 55
  • 1
  • 5

1 Answers1

6

You can do it by this way:

1/ Create a specific method in the UserRepository class:

public function findByNameAndEmail()
{
    $query = $this->createQueryBuilder('u')
        ->select('u.name, u.email') // where name & email are properties of your User entity
    ;

    return $query->getQuery()->getResult();
}

2/ And, call it in your controller:

public function someAction()    
{
    $users = $this->getDoctrine()->getRepository('AppBundle:Users')->findByNameAndEmail();

    return $this->render('livre/users.html.twig',array(
        'users' => $users,
    ));
}
scoolnico
  • 3,055
  • 14
  • 24
  • if for any reason you need objects and not just an array result have a look at PARTIAL syntax (which is partly hydrating your object): http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/partial-objects.html – LBA Oct 22 '15 at 08:23