voyeger
voyeger

Reputation: 139

Conditional Cfloop code to place AND at first loop

Using the following query, I am trying to do a simple case here when the first record it encounters it should basically add "AND" and for the remaining conditions, I want to add OR

Here is my try

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
   <cfset age = trim(htmlEditFormat(lcase(age)))>
   <cfloop list="#age#" index="k">
       or age between #ListFirst(k,'-')# and #ListLast(k,'-')#
   </cfloop>
</cfif>

trying to make it work like this

and (age between 18 and 20 
or age between 20 and 25 
or age between 25 and 30)

I am not getting where I should add a condition to add parenthesis and the AND operator.

Upvotes: 0

Views: 185

Answers (2)

Fish Below the Ice
Fish Below the Ice

Reputation: 1271

An alternative that doesn't require an if block and would work for any type of loop:

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
   <cfset age = trim(htmlEditFormat(lcase(age)))>
   <cfset expressionSeparator = "">
   AND (
   <cfloop list="#age#" index="k">
       #expressionSeparator#
       age between #ListFirst(k,'-')# and #ListLast(k,'-')#
       <cfset expressionSeparator = " or ">
   </cfloop>
   )
</cfif>

Upvotes: 1

Matt Busche
Matt Busche

Reputation: 14333

You could do something as similar as adding a false statement and then looping through everything else as needed

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
  <cfset age = trim(htmlEditFormat(lcase(age)))>
  AND (1 = 2 --always returns false
  <cfloop list="#age#" index="k">
    OR age between #ListFirst(k,'-')# and #ListLast(k,'-')#
  </cfloop>
  )
</cfif>

This is what you were trying to do

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
  <cfset age = trim(htmlEditFormat(lcase(age)))>
  AND (
  <cfloop list="#age#" index="k">
    <cfif listFirst(age) NEQ k> OR </cfif> --if it's not the first iteration, add the OR
    age between #ListFirst(k,'-')# and #ListLast(k,'-')#
  </cfloop>
  )
</cfif>

Upvotes: 2

Related Questions