Search code examples
coldfusioncoldfusion-9cfloop

CFLOOP Duplication


I have a drop down list that is generated by two loops. The inner loop generates a series of numbers ie from 0 to 23. The outer loop, is a query loop that selects the correct value from the 23 numbers based on the values stored in my database.

My issue here is that those two loops conflict that results in displaying the numbers from 0 to 23 twice. How can keep both loops but avoiding this issue? This problem also cause issues when the form is submitted by trying to submit the form twice and deleting the user's input.

This is my code:

<select id="openHours#CountVar#" name="openHours#CountVar#">
 <cfloop query="doctorHours" >                
   <cfloop from="0" to="23" index="OpenHours"> 
   <option value="#openHours#"
      <cfif TimeFormat(doctorHours.openTime,'HH') EQ OpenHours AND CountVar EQ doctorHours.day > selected="selected"</cfif>>#OpenHours#</option>
   </cfloop>
  </cfloop>
</select>

This is my CFDUMP for that query

query
RESULTSET   
query
    CLOSETIME           DAY DOCTORID            OPENTIME
1   1970-01-01 16:00:00.0   4   2011041516290025478779  1970-01-01 10:00:00.0
2   1970-01-01 16:00:00.0   1   2011041516290025478779  1970-01-01 13:00:00.0
3   1970-01-01 16:00:00.0   2   2011041516290025478779  1970-01-01 13:00:00.0
CACHED  false
EXECUTIONTIME   0
SQL select doctorID, opentime, closetime, day from doctorBusinessHours where doctorID='2011041516290025478779' 

Solution

  • You should return only the hours you need and then loop for the dropdownlist creation:

    DATEPART(hh,yourdate) will return the hours for your datetime value:

    <cfquery name="doctorHours" datasource="#ds#">
        SELECT doctorID,DATEPART(hh,openTime) As OpenHours, DATEPART(hh,closetime) As CloseHours 
        FROM   doctorHours 
        WHERE  day = #CountVar#
        AND    doctorID='#docID#'
    </cfquery>
    

    ValueList will transform your query results into a list:

    <cfset openTimesList = ValueList(doctorHours.OpenHours) />
    <cfset closeTimesList = ValueList(doctorHours.CloseHours ) />
    

    ListContains will return the index of the value within your list:

    <select id="openHours#CountVar#" name="openHours#CountVar#">
        <cfloop from="0" to="23" index="OpenHours"> 
           <option value="#openHours#"
               <cfif ListContains(openTimesList,OpenHours) NEQ 0 > 
                  selected="selected"
               </cfif>
           >#OpenHours#</option>
       </cfloop>
    </select>
    

    You can use the same strategy for the closeTimesList.