0

I have custom Question objects which I render into html form elements. I want to be able to dynamically create these objects and generate a dynamic html form from them. The question object has a String property to hold the result from the form. How can I get this to work in Spring?

The way I have it working (which doesn't seem ideal), is I have a bean to back the custom form. This bean has two properties: a List to hold the questions to be displayed and a List to hold the results. The JSP has a tag which tells it to use the bean as a model attribute. Then I have a custom JSP tag that takes the List and renders them into form elements. The elements are given IDs of answer[n] and Spring will put the results of the form into the List property in the backing bean.

Does anyone know how I can do this better?

Buns of Aluminum
  • 2,439
  • 3
  • 26
  • 44
  • This seems similar to my old question http://stackoverflow.com/questions/890250/better-way-for-dynamic-forms-with-spring – NA. Jan 09 '11 at 13:50
  • 1
    It does. Why didn't you select an answer? – Buns of Aluminum Jan 10 '11 at 22:42
  • [Here][1] is the solution I implemented. [1]: http://stackoverflow.com/questions/9671640/spring-3-mvc-managing-a-one-to-many-relation-within-a-dynamic-form-using-a – sp00m Apr 03 '12 at 21:34

1 Answers1

1

My problem was a lack of experience.

I ended up with this (much simplified for explanation):

My bean has the following fields: String questionType, String questionText, String answer. My list of beans is List questions.

When I generate the HTML from the list of beans, I just need to make the id/name of each form element match up with the name of the list, and the position of the bean within the list.

So, if my list of questions looks like this:

[0] {questionType="TEXT", questionText="What is your name?", answerText=null}
[1] {questionType="TEXT", questionText="What is your quest?", answerText=null}
[2] {questionType="TEXT", questionText="What is your favorite color?", answerText=null}

Then I need to generate the following HTML when I loop through the list:

<div class="question">
    <p class="questionText">What is your name?</p>
    <input type="text" id="questions[0].answerText" name="questions[0].answerText" />
</div>
<div class="question">
    <p class="questionText">What is your quest?</p>
    <input type="text" id="questions[1].answerText" name="questions[1].answerText" />
</div>
<div class="question">
    <p class="questionText">What is your favorite color?</p>
    <input type="text" id="questions[2].answerText" name="questions[2].answerText" />
</div>

When the form is submitted, Spring will find those beans and call setAnswerText(String value) on them with the form data.

I hope this helps someone else stumbling at the beginning of their Spring MVC journey.

Buns of Aluminum
  • 2,439
  • 3
  • 26
  • 44