How to echo first field which is not empty

Hi.

So basically I have 4 fields, field-1, field-2, field-3, field-4. Now in my template, I just need to print one content from any of those fields. For example, if field-1 is NOT empty then it will echo the value. If it’s empty then it will check the next field so on.
I’m don’t know much about php so I’ve been just googling and copy pasting some if statements but still cannot make it to work.

Thanks in advance.

You can use an if-elseif-else statement:

<?php
if($field1->isNotEmpty()) {
  //print field1 content
}
elseif($field2->isNotEmpty()) {
  //print field2 content
}
// more elseif statements ...
else { //there is nothing to print here; }

I don’t even know but I think I’ve tried a similar code yesterday and it didn’t work. Maybe I missed something. Gotta try this again later. Thanks.

If you can’t get it to work, come back and post your code here in the forum.

By the way: This is a perfect use case for a controller or a page model to keep logic out of your template.

If you want to put your code into a controller as @flokosiol rightly suggests, all you need to do is fill a variable depending on result and pass that to the template:

<?php

return function($site, $pages, $page) {

<?php

if($field1->isNotEmpty()) {
  $content = $field1;
}
elseif($field2->isNotEmpty()) {
   $content = $field2;
}
// more elseif statements ...
else { //there is nothing to print here; }
 

  return compact('content');

}; 

Does controllers work on snippets? I’m building a one-pager website based on the Kirby docs. I’ve read the controllers doc and it says should be the same file with the template. I only have 2 templates, the home and default. All my other pages are just snippets.

@texnixe Your original code works great btw. Thanks.

You cannot have controllers for snippets, however, you can put the logic for such a one-pager snippet into the controller of the page template, where it is used. In case of a one-pager, this is usually the home.php controller.