CakePHP 5 - NumberHelper::currency() throwing error when value is null

Hi all,

I have been working through migrating my app to CakePHP 5. One major breaking change I’ve run into is, whenever I call $this->Number->currency($value) where $value is null I get an error. Previously this method would treat null as a zero value and give me e.g. $0.00

I’m not sure if this is an explicit change or just a side-effect of upgrading to PHP 8.2 or using more strict typing or something. Presumably this is the expected behaviour? My workaround seems to be replacing every instance like this with $value ?? 0 or something to that effect. I’m not sure if I could possibly override the number helper and allow it to convert null to 0 before calling the parent?

Thanks

Thats expected. You need to check the value before outputting it via the number helper.

1 Like

try this

$this->Number->currency(@$value) or $this->Number->currency(doubleval(@$value))

1 Like

Why don’t you simply use mutators in your entity where you can define how the value will be displayed through the getter method? For example:

    // Getter for the 'value' field
    protected function _getValue($value)
    {
        // Format the value as you want it to be displayed
        return $value ?? 0;
    }

    // Setter for the 'value' field
    protected function _setValue($value)
    {
        // Return the original value without formatting for saving to the database
        return $value;
    }
1 Like

Oh yeah that makes sense! Thanks. It would definitely tidy up my templates to do it this way!

Fortunately this only really comes up when I am joining aggregated data onto my queries, so I won’t need to worry about setters.

1 Like

Dont use @ - thats a dangerous code smell, as it will usually throw exceptions on type issues.
Instead use ternary:

<?= $order->total ? $this->Number->currency($order->total) : '-' ?>

for non-int values (e.g. decimal or float)

You can check otherwise for !== null here.

2 Likes