ColdFusion 将表单数据添加到操作页面上的数组

ColdFusion add Form data to array on action page

问题: 我有一个 HTML 表单,在提交时有 60 多个输入 我想使用 ColdFusion 将所有值保存到操作中的数组中页。有没有更有效的方法来保存所有 60 多个输入的值,而不必一次一提?

我正在寻找某种循环或类似过程,以节省我在操作页面中写下所有输入名称的时间。

如果需要,我可以提供我的代码示例,但它们只是标准的 HTML 表单输入(文本和选择),表单底部有一个提交按钮。

注意:看到您对您的 OP 的评论后,您希望批量插入到一个数据库字段中。你应该小心这一点。虽然现在很容易,但它会使在查询中处理数据变得非常非常困难,并且在 Cold Fusion 中稍微有点困难。


这应该有效

<cfset fArr = ArrayNew(1)>
<cfset fcount = 1>
<cfloop list="#form.fieldnames#" index="f">
  <cfif not listfind("bad,field,names",f)>
    <cfset fArr[fcount] = form[f]>
    <cfset fcount = fcount + 1>
  </cfif>
</cfloop>

CFIF 使您可以省略您可能喜欢的字段名称。如果你想收集每一个,只需将其删除。也许您有一个名为“gobtn”的提交按钮,您不想将其收集到数组中。您可以使列表 gobtn 像 <cfif not listfind("gobtn",f)>

你可以对任何范围或结构使用类似的东西,除了它们通常没有字段名属性或类似的东西,但 Cold Fusion 有函数 StructKeyList(),它也适用于表单scope 但不幸的是 StructKeyList(form) 还包括字段 fieldnames 这可能会很烦人,使用内置变量更容易。

使用 URL 范围进行演示(功能与结构相同)

<cfset fArr = ArrayNew(1)>
<cfset fcount = 1>
<cfloop list="#StructKeyList(url)#" index="f">
  <cfif not listfind("bad,field,names",f)>
    <cfset fArr[fcount] = url[f]>
    <cfset fcount = fcount + 1>
  </cfif>
</cfloop>

(Chris Tierney 对 ArrayAppend 的使用是正确的 btw,你可以这样做更合理)。我不知道为什么我没有包括那个。

另外ArrayNew(1)[]也是一样的,但是CF的早期版本不支持,所以我习惯性的用ArrayNew(1)来回答。

<cfset fArr = ArrayNew(1)>
<cfloop list="#StructKeyList(url)#" index="f">
  <cfif not listfind("bad,field,names",f)>
    <cfset ArrayAppend(fArr,url[f])>
  </cfif>
</cfloop>

鉴于您的一些评论..

另一种选择是 SerializeJSON

你可以做到

<cfset formCopy = Duplicate(form)>
<!--- We have to duplicate the struct so that we can safely modify a copy without affecting the original --->
<cfset DeleteItems = "fieldnames,gobtn">
<cfloop list="#deleteItems#" index="df">
  <cfset StructDelete(formCopy,df)>
</cfloop>
<cfset ForDBInsert = SerializeJSON(formCopy)>
<!--- ForDBInsert now contains a JSON serialized copy of your data. You can insert it into
  the database as such, and call it back later. --->

回调

<cfquery name="getFD">
  select FormDump from Table
</cfquery>

<cfoutput query="getFD">
  <cfset ReBuild = DeserializeJSON(FormDump)>
  <!--- You now have a struct, Rebuild, that contains all the fields in easy to access format --->
  <cfdump var="#ReBuild#">
</cfoutput>
var fieldNameArray = listToArray(form.fieldNames);
var formArray = [];

for( fieldName in fieldNameArray ) {
    if( fieldNamme != "fieldNames" ) {
        arrayAppend( formArray, { name = fieldName, value = form[fieldName] } );
    }
}