文章作者 : Kakusoo [ linkfoxo@yahoo.com ] Web URL : http://
上载日期 : 2000-11-21
The Situation: You have multiple items, each of which have multiple options that
a user can select from. You want something that looks like this:
When the form is submitted, you want to insert separate records into a database for
each row (or composer in this case).
The Solution: This is really a variant on another tutorial called "nested
loops". Here, I'll show you how to use this for input fields. We start off with a
list of composers and another list of time periods. I'll put these both in separate arrays
of only one dimension. (I could use a list instead of an array for this, but arrays are a
little easier to loop over.)
<cfset composers = ArrayNew(1)>
<cfset composers[1] = "Beethoven">
<cfset composers[2] = "Schumann">
<cfset composers[3] = "Hindemith">
<cfset composers[4] = "Glass">
<cfset composers[5] = "Monteverdi">
<cfset timePeriods = ArrayNew(1)>
<cfset timePeriods[1] = "Early">
<cfset timePeriods[2] = "Classical">
<cfset timePeriods[3] = "Modern">
You see that for each element in the composers array (i.e. each composer), I
must account for every element in the timePeriods array. I can do this by looping
through timePeriods while I'm looping through composers -- something called a "nested
loop".
<form action="page_name.cfm" method="post">
<table border="1">
<cfloop from=1 to="#ArrayLen(composers)#" index="i">
<tr>
<td>
#composers[i]#
</td>
<cfloop from=1 to="#ArrayLen(timePeriods)#" index="j">
<td>
<input type="Radio" name="#composers[i]#" value="#timePeriods[j]#">
#timePeriods[j]#
</td>
</cfloop>
</tr>
</cfloop>
</table>
<cfwddx action="CFML2WDDX" input="#composers#" output="wddxComposers">
<input type="hidden" name="wddxComposers" value="#wddxComposers#">
</form>
A word about the <CFWDDX> tag: WDDX is a nice piece of magic that
converts any kind of variable (including query resultsets, arrays, and
structures) into a particular kind of string. You can then pass this string
along, just as you would with any other string. When it arrives on the other
end, another <CFWDDX> tag will turn it back into a true CF variable.
If I send the composers array off to the next page, I can loop through this
array again -- this time inserting the values I find into a database. To send the array, I
use the <CFWDDX> tag.
Now, on the page that will process this form, I first convert the WDDX string back into
a ColdFusion array...
<cfwddx action="WDDX2CFML" input="#form.wddxComposers#" output="#composers#">
...and
then loop over it to insert the form values passed to me into a database.
<cfloop from="1" to="#ArrayLen(composers)#" index="i">
<cfquery datasource="dsn">
INSERT INTO aTable(
composer,
timePeriod
)
VALUES(
'#composers[i]#',
'#Evaluate('form.' & composers[i])#'
)
</cfquery>
</cfloop>
|