Acyra
Acyra

Reputation: 16034

Symfony2 FormBuilder with Entity type with no values

I am using an entity type of form element in Symfony2's formbuilder.

 ->add('categories', 'entity', array('required' => false,
            'multiple' => true,
            'expanded' => true,
            'label'=>'Categories (select all that apply)',
            'class' => 'AcmeBundle:Category',
            'query_builder' => function(EntityRepository $er) use ($profile) {
                return $er->createQueryBuilder('u')
                    ->where('u.profile = :profile')
                    ->setParameter('profile', $profile)
                    ->orderBy('u.name', 'ASC');
            }));

There is a case where the database query does not return any values, but Symfony2 still displays the label for the element.

How do I suppress the label altogether for cases where there are no entity results to display? Thanks!

Upvotes: 0

Views: 599

Answers (2)

saamorim
saamorim

Reputation: 3905

Improving the answer of @alainivars since my edit was rejected.

In your associated .twig file add this:

{% if not empty(entity.categories) %}
    {{ form_label(form.categories) }}
    {{ form_errors(form.categories) }}
    {{ form_widget(form.categories) }}
{% else %}
    {% do form.categories.setRendered %}
{% endif %}

That will display it only if it is not empty and marked the setRendered on the field so it doesn't show on the form_rest, thus bypassing your problem.

Upvotes: 0

alainivars
alainivars

Reputation: 216

In your associated .twig file add this:

{% if not empty(entity.categories) %}
    {{ form_label(form.categories) }}
    {{ form_errors(form.categories) }}
    {{ form_widget(form.categories) }}
{% endif %}

That will display it only if it is not empty

Upvotes: 1

Related Questions