Set default value if null in twig - symfony

I am looping my results in twig view..
{% for item in items %}
<li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
{% endfor %}
I want to set default value 'User unknown' if the user id in database is NULL .
Like: {% if item.userId is null %} --> than set default value
Note: I am aware of using if else here but as I have this fistName - lastName in numerous palace, I wanted to avoid using if else in every part. I wanted to set that default value everywhere in case userId is null without repeating the code in every place.
How can I accomplish that?

EDIT
You can set a variable by using:
{% set name = item.userId is null ? 'User unknown' : item.userId.firstName ~ ' ' ~ item.userId.lastName %}
If by setting you mean outputting 'User unknown', a simple if else statement would do the trick
{% for item in items %}
{% if item.userId is null %}
<li>User unknown</li>
{% else %}
<li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
{% endif %}
{% endfor %}

It may be easier to set defaults in the code that is rendering the output, where items is being sent to Twig. array_merge is often used for this - $item = array_merge($defaultItem, $item);. Here, $item overrides the value set in defaults.
Within the templates, you can also use the null-coalescing operator ?? on individual fields: {{ item.userId.firstName ?? 'unknown firstName' }}

Maybe a bit late, but Twig seems to have a filter for default values:
https://twig.symfony.com/doc/2.x/filters/default.html

Related

how do I get the raw field values in a twig?

In Drupal 9, I have created a field[description] which is a List in a content type[country]. In the description list, I added two values like name, capital as dropdown. Here is the condition:
if(description==name) { //country name should be displayed) }
if(description==capital) { //the capital name should be displayed }
How do I do this using twig?
I haven't tried coz I had no idea. Can anyone give me solution for this?
Here is the twig code.
{% if country.field_description.value == 'name' %}
{{ country.title.value }}
{% elseif country.field_description.value == 'capital' %}
{{ country.field_capital.value }}
{% endif %}

How to show symfony validation errors?

I try to visualize my error messages from the validator.
When i write the following example:-
{{ form_errors(form.pGWeek) }}
it works fine and i get the message. But my form has 200 fields and so it's not practical.
So i want to iterate over an Array with all messages, at the end of the form like this:
{% if form.name.vars.errors|length > 0 %}
<ul class="form-errors name">
{% for error in form.name.vars.errors %}
{{ error }}
{% endfor %}
</ul>
{% endif %}
But i did not get some messages. As well i tried some another versions.. but nothing worked. I'm using Symfony 2.7.
Can give me somebody a tip?
Thanks for a short feedback.
So you just want to show all errors for all children of a form without displaying them beside each input field?
Then you could iterate over all the children of your form, check if any errors appeared on this children and if so, iterate over all errors of this children. That could be something like that:
{% for children in form.children %}
{% if children.vars.errors is defined %}
{% for error in children.vars.errors %}
{#{{ dump(children) }}#}
{#{{ dump(error) }}#}
{{ dump(children.vars.name ~ ': ' ~ error.message) }}
{% endfor %}
{% endif %}
{% endfor %}
Which result in an error like description: This value should not be blank..
You can make that loop and condition in your controller using dependency injector, and then in your view you iterate that array of errors and put it into a div o wherever you want, I guess there is something like this:
$errors = $this->get('validator')->validate(yourObject);
if (!empty($errors)) {
foreach ($errors as $error)
throw new \Exception($error->getMessage());
}
That is if you want to stop the process and get an Exception, but you want to show that errors, then you make something similar, you only needs to delete that foreach and render your twig template and give it the $errors variable, in your template then you only need to make a for loop for get the errors!

Twig - loop default value

I am trying to print array from the cotroller into the twig temlate. I want to print "-" whenever array is NULL. My problem is that in for-loop case it writes nothing, however single row working fine. Is there some simple way how to do it correctly?
this is not working as i expected
{% for key in keywords|default('-') %}
{{ key~', '}}
{% endfor %}
this is working
{{ key |default('-')}}
You can use an {% else %} construct on a for loop to do something else if the array is null:
{% for key in keywords %}
{{ key~', '}}
{% else %}
-
{% endfor %}
See the documentation here.

compare a input field value to a string or text symfony2

I was trying to learn about framework and Ill be starting under "Symfony", then i got this problem, I create a
{{ form_widget(form.type) }}
equivalent to
<input type="text" class="type" id="type"/>
this element "input" have a value that given by a tab or menu if i click on it, example jumping.how do i compare it to a text using "Symfony" if statement like the logic below.
{% if jumping == "text" %}
//it will do something
{% endif %}
as explained nicely in the symfony docs here you need to use the form.vars.value to get the input field's value
so for someting like {{ form_widget(form.name) }} you would access the values by doing {{ form.vars.value.name }}
in your case it would be
{% if form.vars.value.name == "text" %}
//do something
{% endif %}

Twig: filter in an if condition

I want to use an filter in an if condition in Twig. The reason for this is a Symfony2 attribute, which I can't compare directly, I have to change it beforehand. I have started with this code:
{% if app.request.attributes.get('_controller')|split('::')|first == 'some\controller\name' %}
do something
{% endif %}
Unfortunately this does not function. So I thought I would use set before the comparison:
{% set controller = app.request.attributes.get('_controller')|split('::')|first %}
{% if controller == 'some\controller\name' %}
do something
{% endif %}
{{ controller }} {# would print 'some\controller\name' #}
Guess what? "do something" is not printed, even if the variable controller now exists and has the value I compare it with. What am I doing wrong?
Ok I tested it, Twig has a strange behavior. "\" is escaped or something like this.
I extended my twig environement with the var_dump function, check this:
{{ var_dump("Sybio\Bundle\WebsiteBundle\Controller\MainController") }}
//string(48) "SybioBundleWebsiteBundleControllerMainController"
{{ var_dump(app.request.attributes.get('_controller')|split('::')|first) }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"
{{ var_dump("Sybio\\Bundle\\WebsiteBundle\\Controller\\MainController") }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"
That's why your test is always false.
You need to double the backslashes of your compared string...
{% if app.request.attributes.get('_controller')|split('::')|first == 'some\\controller\\name' %}
do something
{% endif %}

Resources