Noah Duncan
Noah Duncan

Reputation: 510

How do I override an Entity Type's label in Symfony 2 with multiple field values?

I'm trying to make a custom form in Symfony 2. I've got a Entity field type that I'm trying to render as expanded / multiple. The default rendering for each entity is something like the following pseudo code:

<input type="checkbox" value='$entity->id'><label>$entity->id</label>

This is pretty terrible. I'd like to get symfony to render each entity with something more detailed like:

<div>
    <input type="checkbox" value='$entity->id'><label><strong>$entity->name</strong>
    <div>$entity->detail</div></label>
</div>

The documentation doesn't mention how to access specific fields of an entity when rendering a form. Does anyone have an idea of how to tackle this?

Thanks!

Upvotes: 0

Views: 1703

Answers (3)

Bartłomiej Wach
Bartłomiej Wach

Reputation: 1986

The default layout for all forms, if you use the full stack framework, is placed in

vendor\symfony\symfony\src\Symfony\Bridge\Twig\Resources\views\Form\form_div_layout.html.twig

you can see what happens there which is that entity is rendered as

{% block choice_widget_expanded %}
{% spaceless %}
    <div {{ block('widget_container_attributes') }}>
    {% for child in form %}
        {{ form_widget(child) }}
        {{ form_label(child) }}
    {% endfor %}
    </div>
{% endspaceless %}
{% endblock choice_widget_expanded %}

if you want to owerwrite rendering of a row of an entity field, as @Manocho mentioned, you can refer to http://symfony.com/doc/current/cookbook/form/form_customization.html and overwrite that block in your template file and then add

{% form_theme form _self %}

so twig will search for overwritten blocks in the same twig file it is rendered in

Upvotes: 1

dmnptr
dmnptr

Reputation: 4304

You can access specific fields on an entity like this - {{ form_widget(form.your_choice_field.0) }} for the first item, {{ form_widget(form.your_choice_field.1) }} for the second and so on.

your_choice_field is a form field, which could be choice or entity.

{{ form_widget(form.your_choice_field.0) }} allows you to access individual items in choices array.

Upvotes: 1

Ziumin
Ziumin

Reputation: 4860

Have you tried adding property option when adding your entity field as described here? You can also add __toString method to your entity.

Upvotes: 0

Related Questions