Derple
Derple

Reputation: 63

How to show integer 0 but not empty or NULL in TYPO3 Fluid

In my TYPO3 Fluid template I have a value where I would like to check if its not empty before showing it. My way now:

<f:if condition="{myvalue}">
<div class="myclass">{myvalue}</div>
</f:if>

This works when I type in the backend a value like "test" or "2", and if I dont type anything it won't show the div tag. But when I type in the backend "0", the condition is also not true. How can I fix that the integer 0 will be showed, and if its empty (in database NULL) not be showed? (its very common that the value will be 0)

Btw i tried things like:

<f:if condition="{myvalue} !=NULL">
<f:if condition="{myvalue} >= 0">

But then also the empty value's wil be show. If I do

<f:debug>{myvalue}</f:debug>

I get things like:

myvalue = NULL 
myvalue = 0 
myvalue = "test"

So only the first one must not been shown.

I hope someone can help me, thank you.

Upvotes: 5

Views: 3974

Answers (2)

Stoppeye
Stoppeye

Reputation: 159

I had a similar case, where I wanted to check a fluid variable for 0 or positive integers. A simple >= 0 comparison wouldn't work. In TYPO3 10 LTS I could resolve this problem by doing this:

<f:if condition="{value} === 0 || {value * 1} > 0">
    value is zero or positive integer
</f:if>

(Note: this will also allow integer strings, such as "123" or "1st", but not "val3" - basically as you would expect when casting a string as integer in PHP.)

If you just want to check that {value} is not null or empty (but allow zero as a valid value), you can simplify the condition to:

<f:if condition="{value} === 0 || {value}">
    value is set and not empty
</f:if>

Upvotes: 1

biesior
biesior

Reputation: 55798

There are two solutions first is transient field in your model of bool type which getter just checks if value is not null, but additionally returns true if value is 0 (actually in most languages 0 IS a value)

Second solution is even more universal, it's just writing custom ViewHelper, which will allow uou to check if value is 0 or has value:

<?php
namespace VENDOR\YourExt\ViewHelpers;

class notEmptyOrIsZeroViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {

    /**
     * @param mixed $value Value to check
     *
     * @return bool the rendered string
     */
    public function render($value) {
        return ($value === 0 || $value === '0' || $value) ? true : false;
    }
}

So you can later use this as a condition for common <f:if > condition like:

<f:if condition="{yourNameSpace:notEmptyOrIsZero(value: myValue)}">
    <f:then>Now it recognizes 0 as a value</f:then>
    <f:else>It still DOESN'T recognize 0 as a value</f:else>
</f:if>

Upvotes: 7

Related Questions