简体   繁体   中英

Symfony2: How to display choices field text?

I generate a doctrine CRUD files first. This form has a choice field that has choices value and names. newAction and updateAction uses this. But index(list)Action display a raw value, not name. How to best way to display choices name in index.html.twig?

SampleFormType.php

$builder->add('name')
    ->add('isActive', 'choice', array(
        'choices' => array(false => 'Inactive', true => 'Active'),
        'expanded' => true,
        'multiple' => false,
    ));

index.html.twig

{% for entity in entities %}
<tr>
    <td>{{ entity.name }}</td>
    <td>{{ entity.isActive }}</td>
    <!-- Show '0' or '1', not 'Inactive' or 'Active' -->
</tr>
{% endfor %}

Shoud i make filter of twig extension or convert value to name in controller?

There are many different ways to do this. A simple one is a basic conditional

{{ entity.isActive ? 'Active' : 'Inactive' }}

But this could very quickly violate DRY if you need to use this value in more than one place.

I think twig extensions should be reserved for things that aren't so domain specific. You could use macros , but those usually serve another purpose as well.

The more architecturally sound idea is to not send Entity objects to the view at all. In a system of good MVC separation, the View and the Model don't interact directly.

Consider how Symfony already handles views for complex objects like forms - you can adopt a similar pattern for your entities. You could even consider using something like Fractal , which was designed for hypermedia APIs but could definitely be used for view objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM