Shortest conditional logic to insert field value or default value

Hi there,

in my Kirby projects, I have to constantly check if a field is empty and if so, insert a default value, if not insert the field’s value instead.

Currently I do this by either of these two methods

// #1
$secs = $film->runtime_sec()->isEmpty() ? "00" : $film->runtime_sec();

// #2
$secs = r($film->runtime_sec()->isEmpty(), "00", $film->runtime_sec());

In both methods $film->runtime_sec() needs to be evaluated twice. Is there a shorter way that works for Kirby fields, maybe something like the short circuit pattern in JavaScript?

var secs = film.runtime || "00";

Thanks!

You can use the Null Coalescing Operator in combination with value():

$secs = $film->runtime_sec()->value() ?? 'default':
1 Like

Alternatively, you can use or() as well here i think…

1 Like

I always forget about this handy method…

Great, thanks! Both methods will make my code a lot cleaner.

One more related question though. Say I want to check if a field is empty or not and if not, I want to return the value with some alteration. See this example:

$price = $product->price()->isEmpty() ? "free" : $product->price() . " €";

In this case I cannot use or, as I would need to alter the field value (add a symbol). Is there any short and elegant way to achieve this, without having to do $product->price() twice?

No, I don’t think so, because you don’t want to add to free, so you would need a condition.

Ok, thanks, just wanted to make sure that I am not missing out on some secret Kirby method. :wink:

You could also create your own magic method.
A similar example would be this idea which was solved by a custom page method: New wrap() method · Issue #431 · getkirby/ideas · GitHub

2 Likes

I think I might just do that, because I really need this all the time: “Take some field value with a tiny alteration or if the field is empty some default fallback”. Might even be a good on board method I think.