Symfony 4 Search Form by entity type (M:N), results show only fields from form, other missing

I have 2 entities: Worker (id, firstname) and Profession (id, title).

I have some workers with one or more professions.
When I open website I see worker data with all professions from workers. For example:

ID: 2 – Tom – teacher, driver

Next, I created search form where i can choose by entity type some of profession and click search.
After this I see list of workers but some o professions dissapear, I see only this professions what i choose in form. For example when I try search drivers:

ID: 2 – Tom – driver (text: teacher profession dissapear from results)

It should be ID: 2 – Tom – teacher, driver (same like before but list should show only persons with driver profession, but text about rest of profession should be here to read)

Code from search controller:

$repository = $this->getDoctrine()->getRepository(Worker::class);
$form = $this->createForm(WorkerSearchType::class, null, [
    'method' => 'GET',
]);

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $professions = $form->get('professions')->getData();

    $qb = $repository->createQueryBuilder('w')
        ->select('w, p')
        ->leftJoin('w.professions', 'p');

    if(isset($professions) && count($professions)>0){
        $qb->andWhere('p.id IN (:professions)')
            ->setParameter('professions', $professions);
    }

    $qb = $qb->getQuery();
}

if(!isset($qb)){
    $qb = $repository->createQueryBuilder('w')
        ->select('w')
        ->orderBy("w.created", 'DESC')
        ->getQuery();
}

Fragment of form type:

$builder
            ->add('professions', EntityType::class, array(
                'class' => Profession::class,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->orderBy('u.name', 'ASC');
                },
                'choice_label' => 'name',
                'multiple' => true,
                'expanded' => false,
                'required' => false,
                'label' => false,
            ))
;

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *