ColdFusion 101: Looping over Months

A reader asks, “Is it possible to to loop through the remaining months of the current year and then show those in a form select field?” I like this question because a) it is simple and b) it is a nice “real world” type question that people are likely to encounter while working on a web site. Let’s take a simpler approach and first show how to make a drop down containing all the months:

<form>
<select name="month">
<cfloop index="x" from="1" to="12">
   <cfoutput><option value="#x#">#monthAsString(x)#</option></cfoutput>
</cfloop>
</select>
</form>

The only real ColdFusion in this form is the MonthAsString() function. As you can imagine, it takes the number of a month and returns the name of the month. Once again, I could have easily typed out all 12 month names, however, this solution will be automatically localized in non-English environments. To see an example of this, simply add <cfset setLocale(“fr_FR”)>\> as the line in the code above.

So, let’s now modify the code to work as the reader desired. The logic is - show the remaining months of the year. To me, that means every month after now. It also means that in December, we show nothing. I’ll show the code first, then describe it.

<form>
<cfif month(now()) is 12>
   Sorry, but you cannot select a month.
<cfelse>
   <cfset startMonth = month(now()) + 1>
   <select name="month">
   <cfloop index="x" from="#startMonth#" to="12">
      <cfoutput><option value="#x#">#monthAsString(x)#</option></cfoutput>
   </cfloop>
   </select>
</cfif>
</form>

The first thing of interest here is the <cfif> block. We use the Month function to determine if this is December. If so, we output a message to the user. If it isn’t December, we create a variable equal to the current month’s number plus one. We then slightly modify the <cfloop> to range from that new number to 12.

p.s. Would you believe spammers are actually using the “Ask a Jedi” form to send me spam? I truly think there is a special place in Hell for these folks.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments