Coldfusion: Inserting parent/child dynamic form fields
need some help thinking through h开发者_StackOverflow社区ow to approach this.
I have a dynamic form that allows the user to create questions. They can have one to many questions.
The questions can then in turn have one to many answers associated with them.
The UI is driven by jquery and is done. The field names post to the processing page like so:
Questions look like: Question1, Question2, Question3, etc.
Answers look like: Question1-Answer1, Question1-Answer2, Question2-Answer1, etc
I know I need to loop over the questions, insert, grab the new ID, and apply it to the answer to build the relationship between question and answer in my database.
As for how to technically approach this, my first guess is to build an array of questions with the second column of the array being an array of answers. I'd then just loop over the array.
Help? :) Thanks!
Instead of inserting all your questions and answers in a bulk statement with lots of looping & logic, insert them as the user adds them. i.e. sounds like you will need an "add another question" button, using javascript[Ajax?] to add another question field - use that to insert the question in the database as well.
Something like this will do the trick :
<cfloop list="#form.fieldNames#" index="field">
<!--- yes, i used len('question') rather than '8' for readability--->
<cfif len(field) gt len('Question') AND left(lCase(field), len('Question')) eq 'question' and listLen(field,'-') eq 1>
<cfset question = form[field]>
<!--- insert question into database --->
<cfloop list="#form.fieldNames#" index="answerField">
<cfif findNoCase(field, answerField) and listLen(answerField) gt 1>
<cfset answer = form[answerField] >
<!--- answer for same question, insert into database --->
</cfif>
</cfloop>
</cfif>
What we're doing is looping over the fields from the form and finding questions. When we find one, we insert into the database. Then we loop to find the answers for that question and insert them into the database
How we're finding a question field :
<cfif len(field) gt len('Question')
AND left(lCase(field), len('Question')) eq 'question' and
listLen(field,'-') eq 1>
if the field is longer than the string 'question' and the left 8 chars is 'question' and there isn't a dash with more chars
How we find an answer :
<cfif findNoCase(field, answerField) and listLen(answerField) gt 1>
if the question field is part of the name and it has a dash, so more than one element
Make sense?
I worked on a similar problem before, except we had up to 5 levels of heirarchical data on the form. In that case, we used Javascript to build up a structure of the data and turn it into JSON and send it over AJAX to the server. CF then just used JSONDeSerialize() to turn it into a heirarchical struct-of-structs in one line of code. You're pushing more work into the client, but that's the place where the structure is already defined, so it make be easier to do it there?
精彩评论