9

This seems like a very basic question but I assure you I've run the gamut of solutions for this to work and I still haven't managed to find a solution.

The problem is this:

  1. A twig value will be set with a value of 1, 0, or null by a select box and the value will then be used to set the selected value for that box.

  2. There are two filters that are chosen - 1 for active, 0 for inactive.

  3. If no value is set and the twig value is set empty (null) the option for 0 is always selected.

The twig code in question is as follows: <option value="null">Select an Option</option> <option value="1"{% if filterStatus == 1 %} selected{% endif %}>Active</option> <option value="0"{% if filterStatus == 0 %} selected{% endif %}>Inactive</option>

Is what I expected to use. Below is one of many variations I attempted:

{% if filterStatus == 0 and not filterStatus != 'null' %}

I just can't seem to ensure the value is 0.

Also don't be fooled by the "null" value in the option value attribute. This is used in routing, but translates to a literal NULL in the system and not a string by the time it makes it to twig.

Any help is greatly appreciated.

Ryan Rentfro
  • 1,642
  • 3
  • 16
  • 18
  • possible duplicate of [How to check for null in Twig?](http://stackoverflow.com/questions/3264889/how-to-check-for-null-in-twig) – Med May 26 '15 at 08:46

2 Answers2

17

The way of checking for not null is:

{% if var is not null %}

But you can use the same as function:

{% if var is same as(0) %}
    {# do something %}
{% endif %}

Ref: http://twig.sensiolabs.org/doc/tests/sameas.html

magnetik
  • 4,351
  • 41
  • 58
6

Try this

{% if filterStatus == 0 and filterStatus is (not) empty %}
Mahadeva Prasad
  • 709
  • 8
  • 19