PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 9, 2022

[FIXED] Set default value if null in twig

 March 09, 2022     symfony, twig     No comments   

Issue

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?


Solution

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 %}


Answered By - ImAtWar
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing