Search code examples
formscoldfusioncheckboxcfform

Is there an easier way to manipulate checkboxes in coldfusion?


Basically, I have stored information in a database field and I want to display it again through a form.

The original form has the same checkboxes but they are always empty. The user can check the boxes off and the values are put into the database.

Graduate Courses: Fall? Spring? Summer? Stored as a list in a column named grad. (F, M, S)

They have the option to save this lovely form as a draft. When they come back to the draft I need to display what they might have already checked.

  <cfif listContains(#grad#, "F") is not 0>
  <input type="checkbox" name="grad" id="grad" value = "F" checked />
  <cfelse>
  <input type="checkbox" name="grad" id="grad" value = "F"  />
  </cfif>
  <cfif listContains(#grad#, "S") is not 0>
  <input name="grad" type="checkbox" id="grad" value = "S" checked />
  <cfelse>
  <input name="grad" type="checkbox" id="grad" value = "S" />
  </cfif>
  <cfif listContains(#grad#, "M") is not 0>
  <input name="grad" type="checkbox" id="grad" value = "M" checked />
  <cfelse>
  <input name="grad" type="checkbox" id="grad" value = "M" />
  </cfif>

Is there an easier method to doing this with cfform code?

Just curious. :)


Solution

  • I do it like this, as I don't really use <cfform>:

    <cfloop list="F,S,M" index="g">
      <input type="checkbox" name="grad" id="grad_#g#" value="#g#" #CheckedIf(ListFind(grad, g) gt 0)# />
    </cfloop>
    
    <!--- ... --->
    <cfscript>
      function CheckedIf(expression) {
        if (arguments.expression) return 'checked="checked"';
        return "";
      }
    </cfscript>
    

    But the ColdFusion docs state:

    [since] ColdFusion MX: Changed the cfform tag preserveData attribute behavior: if it is set to True, ColdFusion checks radio and check box values only if their value matches the posted value for the control.

    So yes, <cfform> can help you with this. Use <cfparam name="FORM.xyz" default="foobar"> to emulate the "posted value" for normal requests.