Handling Potentially Empty Fields
For this guide we will use the example of a contact record, where we want to build a title using the contact’s first and last name. However, we may not always have both names available.
Why we have to handle missing field values with care
Section titled “Why we have to handle missing field values with care”In the screenshot above all is good but if the contact’s last name is missing, it does not look right. We need to ensure that our title is still meaningful even if some information is missing.
The solution
Section titled “The solution”To handle potentially empty fields, we can use a combination of conditional logic and default values in our calculation field. Here’s an example of how we might construct the title:
`${@First Name || ""} ${@Second Name || ""}`
In this code, we are using the logical OR operator (||
) to provide default values for each field. If the @First Name
field is empty, it will default to an empty string, and if the @Last Name
field is empty, it will also default to an empty string.
This way, even if one of the fields is missing, our title will still be meaningful and not look too awkward. However it is not a perfect solution as we may end up with a title that has an extra space if one of the fields is missing.
To further refine our title and avoid extra spaces, we can use the trim()
method to remove any leading or trailing whitespace. Here’s the updated calculation:
`${(@First Name || "").trim()} ${(@Second Name || "").trim()}`.trim()
If we switch to first name missing it is easier to see the difference:
Option One has a space before the second name but in option two (using our
trim
code) there is no leading space.
There are other ways to handle this, for example we could use a conditional (ternary) operator to check if each field is empty and construct the title accordingly. However, the above method is simple and effective for most use cases.
more complex scenarios
Section titled “more complex scenarios”However what happens if we have more options for example we want to include a title (Mr, Mrs, Dr etc) if it is available. We can extend our calculation field to handle this scenario as well:
one way of dealling with this is to just add more or
statements:
`${@Title || ""} ${@First Name || ""} ${@Second Name || ""}`.trim()
again that will mostly work but we can make it better, more reliable and more scaleable by building an object and then joining the values. Here’s an example:
let titleParts = [ @Title?.trim(), @First Name?.trim(), @Second Name?.trim()].filter(Boolean);
let fullTitle = titleParts.join(" ");
fullTitle
This way, we can easily add or remove fields from the title without having to modify the entire string template. It also makes the code more readable and maintainable.