Using a ColdFusion Ternary Operator for an Optional Tag Attribute

Today I had to write a script to process a form and send an email as part of the processing. The form allows the user to specify an email address to bcc, but it’s not required. I’m a big fan of using the Ternary Operator for doing either/or stuff like css classes. So I decided to extend that fandom to set the bcc attribute of the <cfmail> tag if the email specified in the form was valid.

Assumptions for this example:

1. You have validated form.bccEmail as a valid email.
2. You have a default mail server specified in Application.cfc or CFADMIN.
3. You may see more utility in using the Ternary Operator for other conditional cases.

The “magic” is in the bcc attribute below:

    <cfmail to="someone@example.com" 
        bcc="#Len(form.bccEmail)?form.bccEmail:''#" 
        replyto="donotreply@example.com" 
        failto="donotreply@example.com" 
        from="donotreply@example.com" 
        subject="An important message" 
        type="html">
	    Message Body here...
    </cfmail>

Leave a Comment