Get number of choices from entity field in Twig template - symfony

I have a Symfony 2 form for a Doctrine entity with an entity choice field for a ManyToMany relationship. It is possible for the choice field to not have any choices - how can I test for this in Twig?
Example: The form is for a "Deal" entity, which can optionally be assigned to a "Location" entity. I render the "Location" entity field like this:
{{ form_label(edit_form.locations) }}
{{ form_errors(edit_form.locations) }}
{{ form_widget(edit_form.locations) }}
The field is set to render with checkboxes. However, it is possible that no "Location" records will exist. In this scenario the user will see the label "Locations: " but no check boxes. I would like to have a conditional statement that displays a message, something along the lines of this:
{{ form_label(edit_form.locations) }}
{{ form_errors(edit_form.locations) }}
{{ form_widget(edit_form.locations) }}
{% if edit_form.locations.choices|length == 0 %}
You haven't created any Locations yet!
{% endif %}
Anybody know of a way to achieve this?

Just to help others...
In newer versions it would be:
{% if edit_form.locations.vars.choices|length == 0%}
I was actually looking to do this, so I'll share:
If you had an embedded form and you wanted to do the same type of check except pulling the data from the prototype (in case the form is not generated with any children forms)
{% if form.childForms.vars.prototype.field.vars.choices|length == 0 %}
"childForms" being the embedded form type and "field" being the select field you want the choices out of...

Found it:
{% if edit_form.locations.get('choices')|length == 0 %}

Related

pluralize results if plural in symfony (good practice)

I have a filter bar that let me search some results within my database.
I have a flash message that shows how many results are found when I enter a word inside it.
this is my controller
if ($filter != '') {
$this->get('session')->getFlashBag()->add('info', 'worked!');
}
and this is in my template
{% for message in app.session.flashbag.get('info') %}
{{ message }}
{% endfor %}
so when i research things actually, whether I have 1 result or more it doesn't change my sentence.
résultats is still written with an s as it is hard coded. How can I create something that will allow me to pluralize and singularize a word in my template? Should I go directly in the controller for that ?
EDIT
I used this method directly in the template but I don't think it is a "good practice" one. Any help for making that better?
{{ results.getTotalItemCount }}
{% if results.getTotalItemCount <= 1 %}
{{ 'this.is.your.result'|trans({ '%count%': results.getTotalItemCount}) }}
{% else %}
{{ 'this.is.your.results'|trans({ '%count%': results.getTotalItemCount}) }}
{% endif %}
in translation
this:
is:
your.result: "résultat"
your.results: "résultats"
You should maybe check pluralization in translations here, you can use transChoice() method, it is explained here how to use it.
Here you can see how to use it in twig:
https://stackoverflow.com/a/10817495/5258172
Edit:
your answer in question can be done like this:
this:
is:
your.result: "1 résultat|%count% résultats"
and then in your twig:
{{ 'this.is.your.result'|transchoice(results.getTotalItemCount) }}

Check if YAML field is empty in twig

I have two .yml files, in each one of them is a translation of my website. I reference the fields of the .yml files using twig. In one translation I need a field that in the other I don't. So in one translation I have to reference an empty field. But on the website there is not shown nothing but the "path" of the field. So I want to check if the field is not empty, how is it done?
YAML:
title
1: string
2: ~
HTML/Twig:
<h4> {{ 'title.1'|trans }}<sup>7</sup>
{% if 'title.2' is not empty %}
{{ 'title.2'|trans }}
{% endif %}
</h4>
Website: String title.2
With if 'title.2' is not empty you test a concrete string to be empty, which will never be false. Even if '' != 'title.2'|trans might not work as it could fall back to a default language.
If you explicitly don't want to show a certain text based on the user's locale then test for that. It also makes your code easier to read and to maintain:
{% if 'en' != app.request.locale %}
{{ 'title.2'|trans }}
{% endif %}
Even shorter:
{{ 'en' != app.request.locale ? 'title.2'|trans }}
I would also suggest using short words or phrases to identify translations instead of numbers.

How to use form field value in twig template?

i have a formular and in there I have a collection of entities. In my template i would like to use this:
{% for service in form.services %}
{{ form_label(service) }}
{{ form_errors(service) }}
{{ form_widget(service, {'attr': {'class': service.name}}) }}
{% endfor %}
Is it posiible to fetch a field name from the collection like in my example the field name?
With this i got an error.
Thanks Stefan
In the debug toolbar, click on the form icon. There you can see what your form variable contains. services is probably an array of subforms. You can access a specific subform and then get the value of the "name" property like this: services[0].name.vars.value or you can of course loop through the whole array.

Rendering a choice field type (symfony2) as buttons

I have a problem which I cannot solve. How shall I approach the following: I have a choice field with 4 different entries, which I am rendering perfectly in a select form (twig). However, I would like to show the 4 entries as 4 separate buttons. How do I change the input type of those 4? Or do I have to do anything totally different?
Thanks for your help
-AS
edit (new following question):
Alexandru, thanks for your help. That was very helpful.
I added in the fields.html.twig the following:
{% block _appbundle_action_Style_widget -%}
{% for child in form %}
<input type="button" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{% endfor %}
{%- endblock _appbundle_action_Style_widget %}
However, when I render it it tells me that there is an array to string conversion, which somehow does not work. When I delete the widget attributes, value, and checked parts, the buttons are getting rendered without those then.
You have a few options to choose from:
You can create a new field type, let's call it "button_group", that will extend the "choice" type and write the custom Twig for it, something like this:
https://github.com/symfony/symfony/blob/2.7/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig#L95
You can use the "choice" field type with the option: expanded => true. And create a custom form template for it only for the form you need it in:
http://symfony.com/doc/current/cookbook/form/form_customization.html#what-are-form-themes
Ok I solved my problem. In order to access the value variable I have to use the following {{ child.vars.value }}. With this I can now take the variable and put it into the value tag.
Thanks for your help.

Symfony2 - get value displayed to user for choice field in twig

I am trying to display the "label" (ie, value displayed to user) of a choice field in my twig template. I'm using Symfony 2.3. I just need the label associated with the actual current value of the field.
I finally figured out a way to do it that requires looping through every choice option, but am now wondering if there is a more efficient way? Here is my working code:
{% for choice in form.myfield.vars.choices %}
{% if choice.value == form.myfield.vars.value %}
{{ choice.label }}
{% endif %}
{% endfor %}
I'm looking for something like this (non-working code):
{{ form.myfield.vars.choices[form.myfield.vars.value].label }}
Is there a more efficient way, or is my solution the best possible?

Resources