0

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!

2
  • What happens when say you assign the array to a variable, lets call it $categoryInputAttributes then before calling add() you do unset($categoryInputAttributes['label']); ? Commented Dec 16, 2012 at 3:26
  • That sounds like a solution-- basically run the query before building the form, and building it dynamically. But I'm hoping there's a more Symfony-style approach. Thanks! Commented Dec 16, 2012 at 11:56

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think the twig syntax is "if entity.categories is not empty". But that still doesn't work, it still displays the label.
It is still rendering the main entity "Categories" label with the "form_rest". This almost seems like a Sf2 bug.
0
+50

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.

1 Comment

Thanks! It doesn't work but this first line does: {% if form.categories is not empty %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.