简体   繁体   English

在表单下拉列表中仅返回唯一值symfony 3.4

[英]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. 实体链接到的数据库表包含该组织的多个条目(因为每个组织都有多个用户),我只想返回一个组织名称的实例,而不是返回20个重复的实例。

I have heard there are functions such as distinct() or findOneOrNull but I am not sure how to implement them. 我听说有一些函数,例如distinct()或findOneOrNull,但是我不确定如何实现它们。

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 : 您可以为EntityType指定QueryBuilder

->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. 然后,您必须在UserParentRepository类中添加getUniqueCompanies() ,而DISTINCT会在其中提供帮助。

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. 您应该使用查询生成器: https : //symfony.com/doc/current/reference/forms/types/entity.html#ref-form-entity-query-builder可以使用它创建自己的查询,以获取想要的实体显示。 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. 如果将表中的条目分组,则意味着您将仅链接到doppelgängers的特定行...听起来有些奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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