-1

I am trying to write an If Statement where if "session.checkout.info.abc_1Certificate_1" exists and is not blank then show it. But if "session.checkout.info.abc_1Certificate_1" is blank don't show it.

This is what I have come up with but it is not working properly..

<cfif (len(trim("session.checkout.info.abc_1Certificate_1")))>
  Certificate:&nbsp;#session.checkout.info.abc_1Certificate_1#
</cfif>
Leigh
  • 28,765
  • 10
  • 55
  • 103
David Brierton
  • 6,977
  • 12
  • 47
  • 104
  • 4
    When in doubt, look at your data. In this case, add a cfelse block and output some variables and function results. Start with len(trim("session.checkout.info.abc_1Certificate_1")) – Dan Bracuk Oct 07 '14 at 18:09
  • 7
    Also, due to the double quotes, you are actually checking the length of the literal string `"session.checkout.info.abc_1Certificate_1"` - not the value of a session variable by that name... – Leigh Oct 07 '14 at 18:13

2 Answers2

4

You really rather want something like this:

<cfif structKeyExists(session.checkout.info,"abc_1Certificate_1") AND len(trim(session.checkout.info.abc_1Certificate_1)) GT 0>

This is saying: if there is a key called abc_1Certificate_1 in the structure session.checkout.info AND the length of the value of session.checkout.info.abc_1Certificate_1 with any padding spaces removed is greater than 0, then...

If session.checkout.info.abc_1Certificate_1 doesn't exist, then len(trim(session.checkout.info.abc_1Certificate_1)) would normally throw an error, but since ColdFusion processes the part of the statement to the left of the AND first (and short-circuits the evaluation) CF won't bother to examine the rest of the statement.

Fish Below the Ice
  • 1,273
  • 13
  • 23
  • 2
    See also: [ColdFusion: More efficient structKeyExists() instead of isDefined()](http://stackoverflow.com/q/3956324/3524344) – Fish Below the Ice Oct 07 '14 at 18:28
  • 5
    *processes IF statements from left-to-right* Not quite. The logical `AND` operator is what causes the [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation). – Leigh Oct 07 '14 at 18:51
4

Try this

<cfif isDefined("session.checkout.info.abc_1Certificate_1") 
       AND len(trim(session.checkout.info.abc_1Certificate_1))>
  Certificate:&nbsp;#session.checkout.info.abc_1Certificate_1#
<cfelse>
  session.checkout.info.abc_1Certificate_1 doesn't exist or is blank
</cfif>
Leigh
  • 28,765
  • 10
  • 55
  • 103
Matt Busche
  • 14,216
  • 5
  • 36
  • 61