我正在使用命名格式report[{field-name}] 为我的ColdFusion 应用程序构建一个表单,当使用RoR 或CFWheels 时,它会在后端提供一个名为report 的结构,其中包含我的所有字段名称。我使用的是 FW/1,因此所有表单字段都会放入 RC 范围,而不是保留在表单范围中。我知道可以将我的表单字段转换为 ColdFusion 结构,因为正如我所说,CFWheels 可以做到这一点。我只是不知道如何让我的应用程序做到这一点。
这是我正在谈论的表格的一部分
<dl class="oneColumn">
<dt class="first"><label for="report[name]">Name</label></dt>
<dd><input type="text" name="report[name]" class="text" /></dd>
<dt><label for="report[description]">Description</label></dt>
<dd><textarea name="report[description]" class="textarea"></textarea></dd>
</dl>
Adam 的上下文是正确的,但他的代码片段是错误的。
一个可以工作的函数是这样的:
<cffunction name="$createNestedParamStruct" returntype="struct" access="public" output="false">
<cfargument name="params" type="struct" required="true" />
<cfscript>
var loc = {};
for(loc.key in arguments.params)
{
if (Find("[", loc.key) && Right(loc.key, 1) == "]")
{
// object form field
loc.name = SpanExcluding(loc.key, "[");
// we split the key into an array so the developer can have unlimited levels of params passed in
loc.nested = ListToArray(ReplaceList(loc.key, loc.name & "[,]", ""), "[", true);
if (!StructKeyExists(arguments.params, loc.name))
arguments.params[loc.name] = {};
loc.struct = arguments.params[loc.name]; // we need a reference to the struct so we can nest other structs if needed
loc.iEnd = ArrayLen(loc.nested);
for(loc.i = 1; loc.i lte loc.iEnd; loc.i++) // looping over the array allows for infinite nesting
{
loc.item = loc.nested[loc.i];
if (!StructKeyExists(loc.struct, loc.item))
loc.struct[loc.item] = {};
if (loc.i != loc.iEnd)
loc.struct = loc.struct[loc.item]; // pass the new reference (structs pass a reference instead of a copy) to the next iteration
else
loc.struct[loc.item] = arguments.params[loc.key];
}
// delete the original key so it doesn't show up in the params
StructDelete(arguments.params, loc.key, false);
}
}
</cfscript>
<cfreturn arguments.params />
</cffunction>
我在我的应用程序中(CFWheels 之外)测试了它,它运行得很好。您所做的就是传入一个结构(在我的例子中是来自 FW/1 的 Rc 结构),其中包含应该是结构的内容,但显示为字符串,您将返回一个具有嵌套结构的结构。
Example:
<cfscript>
Struct['hello[world]'] = 1;
Struct['hello[earth]'] = 2;
myhello = $createNestedParamStruct(Struct);
/* Now myhello equals this:
myhello.hello.world = 1;
myhello.hello.eath = 2;
*/
</cfscript>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)