espresso_coffee
espresso_coffee

Reputation: 6110

How to build dynamic cfarguments in ColdFusion9?

I have simple form that has more than 100 fields. All these fields are submitted to cffunction where I have SQL code that will run Insert or Update query. Here is example of my code:

    var formData = $('#'+frmID).serialize();
    $.ajax({
        type: 'POST',
        url: 'Components/MyFunction.cfc?method=userRecord',
        data: formData,
        dataType: 'json'
    }).done(function(obj){
        if(obj.STATUS === 200){
            return true;
        }else{
            return false;
        }
    }).fail(function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
    });

Here is cffunction:

<cffunction name="userRecord" access="remote" output="true" returnformat="JSON">
    <cfargument name="userID" type="string" required="true">
    <cfargument name="userFName" type="string" required="true">
    <cfargument name="userLName" type="string" required="true">
    <cfargument name="userDOB" type="string" required="true">
    <cfargument name="userGender" type="string" required="true">
    <cfargument name="userAddress" type="string" required="true">
    <cfargument name="userCity" type="string" required="true">
    .... And there is more field in this form


    <cfset fnResults = StructNew()>
    //Here is SQL query for insert and update
    <cfreturn fnResults>
</cffunction>

Instead of creating all arguments manually is there a way to use cfloop and collect all the arguments dynamically? I couldn't find any article or example. Would that be a good option or creating arguments manually is better approach? If anyone can help please let me know. Thank you!

Upvotes: 0

Views: 176

Answers (2)

Vineesh
Vineesh

Reputation: 3782

Try passing the data as a structure.

<cffunction name="userRecord" access="remote" output="true" returnformat="JSON">
    <cfargument name="formData" type="structure" required="true">

    <cfloop collection="#arguments.formData#" item="key">
        #key#: #arguments.formData[key]#
    </cfloop>

    <cfset fnResults = StructNew()>
    //Here is SQL query for insert and update
    <cfreturn fnResults>
</cffunction>

Upvotes: 2

Matt Busche
Matt Busche

Reputation: 14333

Pass in the entire form data as a structure.

var formData = $('#'+frmID).serializeArray();
$.ajax({
    type: 'POST',
    url: 'Components/MyFunction.cfc?method=userRecord',
    data: formData,
    dataType: 'json'
}).done(function(obj){
    if(obj.STATUS === 200){
        return true;
    }else{
        return false;
    }
}).fail(function(jqXHR, textStatus, errorThrown){
    alert(errorThrown);
});

<cffunction name="userRecord" access="remote" output="true" returnformat="JSON">
  <cfargument name="form" type="struct" required="true">
  <cfdump var="#arguments.form#">

</cffunction>

Upvotes: 1

Related Questions