Search code examples
phpsymfonydoctrine-ormsymfony4

filter entity fields on symfony controller


How can I choose(filter) on my controller which fields I want (or don't want) to pass to my frontend?

my Controller:

/**
 * @Route("/", name="dashboard")
 */
public function index()
{

    $aniversariantes = $this->getDoctrine()->getRepository(Usuario::class)->aniversariantes();

    return $this->render('dashboard/index.html.twig', [
        'controller_name' => 'DashboardController',
        'aniversariantes' => $aniversariantes
    ]);
}

My repository:

/**
 * @return []
 */
public function aniversariantes(): array
{
 $qb = $this->createQueryBuilder('u')
    ->andWhere('u.ativo = 1')
    ->andwhere('extract(month from u.dtNascimento) = :hoje')
    ->setParameter('hoje', date('m'))
    ->getQuery();

    return $qb->execute();
}

Dump from entity:

enter image description here

What can I do if I don't want to pass the "password" field for example?


Solution

  • If you are just trying to prevent certain fields from being dumped, it is useful to know

    Internally, Twig uses the PHP var_dump function.

    https://twig.symfony.com/doc/2.x/functions/dump.html

    This means you can can define the PHP magic method __debugInfo in your entity

    This method is called by var_dump() when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.

    https://www.php.net/manual/en/language.oop5.magic.php#object.debuginfo

    So in your entity do something like this:

    class Usuario {
        ...
    
        public function __debugInfo() {
            return [
                // add index for every field you want to be dumped 
                // assign/manipulate values the way you want it dumped
                'id' => $this->id,
                'nome' => $this->nome,
                'dtCadastro' => $this->dtCadastro->format('Y-m-d H:i:s'),
            ];
        }
    
        ...
    }