简体   繁体   中英

Return only unique values on form dropdown symfony 3.4

I've made a form that submits the parent organisations of an individual user. The database table the entity is linked to contains multiple entries for the organisation(as there are multiple users associated with each organisation) and I only want to return one instance of the organisations name rather than 20 duplicates.

I have heard there are functions such as distinct() or findOneOrNull but I am not sure how to implement them.

Here is the code from the form:

        ->add(
            'userParent',
            EntityType::class,
            [   

                'class' => UserParent::class,
                'choice_label' => function ($parents) {
                    return $parents->getParent()->getName();
                }
            ]
        )               

You can specify a QueryBuilder for an EntityType :

->add('userParent',
      EntityType::class,
      [   
          'class' => UserParent::class,
          'choice_label' => function ($parents) {
              return $parents->getParent()->getName();
          },
          'query_builder' => function(UserParentRepository $r) {
                                 return $r->getUniqueCompanies();
          },
      ]
    );

Then you'll have to add getUniqueCompanies() in the UserParentRepository class, that's where a DISTINCT will help.

You should use the query builder: https://symfony.com/doc/current/reference/forms/types/entity.html#ref-form-entity-query-builder With that you can create an own query which entities you want to show. But one hind! If you group the entries from the table, means you will link only to one specific row from the doppelgängers... that sound a bit strange.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM