Php 如何使用Symfony formbuilder仅获取实体的特定元素?

Php 如何使用Symfony formbuilder仅获取实体的特定元素?,php,symfony,select,query-builder,formbuilder,Php,Symfony,Select,Query Builder,Formbuilder,在我的formbuilder中,我从实体创建了一个选择框: $options['choice_label'] = function ( $entity) use ($name) { if( $entity->getCategory() == null) { return $entity->getName(); }

在我的formbuilder中,我从实体创建了一个选择框:

$options['choice_label'] = function ( $entity) use ($name) {
                        if( $entity->getCategory() == null) {
                          return $entity->getName();
                        } 
                    };
在类别为空的情况下,我想要一个选项字段,如果不是,我就不想要一个选项字段。 但实际情况是,在类别不为NULL的情况下,我得到了空的选项字段,而我实际上根本不需要选项字段

我得到的是:

<select>
  <option>value with category 1</option>
  <option>value with category 2</option>
  <option>value with category 3</option>
  <option></option>
  <option></option>
  <option></option>
  <option></option>
  <option></option>
  <option></option>
  <option></option>
  <option></option>
</select>

类别1的值
类别2的值
第3类的价值
我需要的是:

<select>
  <option>value with category 1</option>
  <option>value with category 2</option>
  <option>value with category 3</option>
</select>

类别1的值
类别2的值
第3类的价值

我认为有两种方法可以解决您的问题

  • 将实体类型与查询生成器一起使用,以便将正确的选项传递给所选对象

  • 使用选项类型,但将选项写入数组并将其传递给表单项

  • 如果查询生成器抛出类似“无法转换为字符串”的错误,则必须为相关实体定义字符串表示形式。您需要字符串,以告诉类型字段应在选择中显示哪个属性

    以下是解决实体类型问题的方法:

  • 添加一个简单的选择标签
  • 添加更具体的选项标签
  • 指文件的Ofc

    $builder->add('users', EntityType::class, [
        // looks for choices from this entity
        'class' => User::class,
        // select the property which should be used to represent your option in select
        'choice_label' => 'username',
    ]);
    
    
    $builder->add('category', EntityType::class, [
        'class' => Category::class,
        'choice_label' => function ($category) {
            return $category->getDisplayName();
        }
    ])