Coldfusion Variable Checking / Setting Default

/ Published in: ColdFusion
Save to your folder(s)

Copy this code and paste it in your HTML
  1. Need to make sure a variable exists in Coldfusion? Use one of the options below to first check for a value passed from the server/form/whatever. If none is sent, for any reason whatsoever (var error, db error, net hiccup etc...), this code will ensure you still have a variable with a valid defaulted value to ensure 1 problem doesn't become 2.
  4. <!--- Example of Coldfusion's IsDefined Function --->
  6. <!--- This first way is probably easer to understand to newer programmers or people coming from other languages to CF. --->
  8. <!--- Check if the form sent in a value, and if it didn't, then manually set it. Nothing too mindblowing huge here. --->
  10. <cfif isDefined("Form.firstname")>
  11. <cfoutput>Hello, #Form.firstname#!</cfoutput>
  12. <cfelse>
  13. <cfoutput>Hello, stranger!</cfoutput>
  14. </cfif>
  16. <!--- Example of Coldfusions <cfparam> tag used instead --->
  18. <!--- Using cfparam tag is evern easier, less code & more the
  19. technically right way do this in CF (maybe?... lol ) ) --->
  21. <cfparam name="Form.firstname" default="stranger">
  22. <cfoutput>Hello, #Form.firstname#!</cfoutput>
  25. One clean, little, and simple to remember Coldfusion tag replaces a "CFIF" conditional process & all the declararative code you'd need to set those values by hand.This is a pretty small example, but the implications are pretty apparent if you had to check maybe 20 variables etc.


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.