Search code examples
phpsymfonyselectquery-builderformbuilder

How can I get only specific elements of an entity with Symfony formbuilder?


In my formbuilder I create a select box from an entity:

$options['choice_label'] = function ( $entity) use ($name) {
                        if( $entity->getCategory() == null) {
                          return $entity->getName();
                        } 
                    };

In the case the Category is NULL, I want to get an option field and if not I do not want an option field. But what happens is, that in the case the category is not NULL, I get empty option fields, where I am actually do not need an option field at all.

What I get:

<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>

What I need:

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

Solution

  • I see two ways, which will solve your problem.

    1. Use a entity type with a query builder, that passes the right options to your select https://symfony.com/doc/current/reference/forms/types/entity.html

    2. Use a choice type but write the choices to an array and pass it to your form item Symfony2 Form Builder - creating an array of choices from a DB query

    In case that the query builder throws a error like „could not converted into string“ you will have to define a string-representation for the related entity. You need the string, to tell the typeField which attribute should be displayed in the select.

    Here goes the way to solve it for the entity type:

    1. Add a simple choice label
    $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',
    ]);
    
    1. Add a more specific choice label
    
    $builder->add('category', EntityType::class, [
        'class' => Category::class,
        'choice_label' => function ($category) {
            return $category->getDisplayName();
        }
    ])
    

    Ofc refering to the docs https://symfony.com/doc/current/reference/forms/types/entity.html