Search code examples
symfony-formssymfony

Symfony 3 choice list with "visible" entity/document


I have 2 documents category and supplier and a form created from category. I have a nested form category which include supplier. In supplier I have a boolean field visible and I want to be able to only choose from the choice list the supplier set to visible true.

In my category form I tried :

....
->add('suppliers', DocumentType::class, array(
            'class' => 'AppBundle:Supplier',
            'choice_label' => function ($category) {
                if ($category->getVisible == true)
                return $category->getName()

            },
 ....

But all I've got is a choice list with 10 empty fields (without name) and only 1 choice with a name (because only this choice is set to visible true).

Any idea?


Solution

  • I think you need to filter the choices themselves rather than their label.

    This can be done using a custom query used as query_builder option:

    ->add('suppliers', DocumentType::class, array(
        'class' => 'AppBundle:Supplier',
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('c')
                ->where('c.visible', :visible)
                ->setParameter('visible', true);
        },
        'choice_label' => function ($category) {
            return $category->getName()
        },
        // ...
    ))
    

    Hope I correctly understood your need.