0
votes

I am working a dynamic form module for an application where there is a random list of Questions that are submitted as Answers. The problem I'm having is the Answer[] array that is being submitted is not in the same order as specified in the View. (i.e. answer[0].value in the view goes into the controller as answer[3].value). It appears that instead of treating arrays submitted by the view as a true array, they are going into a unordered Set, then converted back into a Array before getting to the controller. Is there any way around this besides treating the arrays as unordered Sets and having to use a manual index.

My controller is basically:

public static void process(Answer[] answers){
   for(int i=0;i<answers.length;i++){
       if(answers[i].question.required){
          Validation.required("answers["+i+"].value,answers[i].value);
       }
   }
   if(Validation.hasErrors()){
     //render the template
   }else{
      //save
   }
}

In my template

   #{list items:questionSet.questions, as:"question"}
      ...
      <div class="#{if play.data.validation.Validation.hasError("anwsers["+question_index+'].value)}error#{/if}">
      <input name="answers[${question_index}].question.id" value="${question.id}"/>
      <input name="answers[${question_index}].value" value="${answers[question_index].value}/>
      <div/>
   #{/list}
1
What if you use List<Answer> to replace Answer[] array?Gelin Luo

1 Answers

1
votes

Note: I am using Play!Framework 1.2.5

You should use List<Answer> for controller method signature instead of Answer[]:

public static void process(List<Answer> answers) {
    ... // your logic
}

And I suggest you to use zero-based-indexing-array on your view, because question_index variable on the view started with value 1. If you insist not to use zero-based-indexing-array, your list size will bigger by 1 element. It is because you start with index 1, and the 0-th index has null value.

To avoid that, your view should like following:

 #{list items:questionSet.questions, as:"question"}
 <div class="...">
    <input name="answers[${question_index-1}].id" value="${...}"/>
    <input name="answers[${question_index-1}].value" value="${...}"/>
 </div>
 #{/list}