2015-06-25 3 views
1

У меня есть следующий HTML-файл. Он использует Thymeleaf:Динамическое формирование имени HTML-формы

<form action="#" th:action="@{/heart2heart/token/__${tokenId}__/}" method="post">    
    <div class="table-responsive"> 
     <table class="table table-striped table-bordered table-hover table-condensed"> 
      <tr> 
       <th style="display:none;"></th> 
       <th th:text="#{service.desc}">Service</th> 
       <th th:text="#{feedback.description}">Feedback</th> 
       <th th:text="#{visit.date}">Date of Visit</th> 
       <th th:text="#{repr.name}">FU Repr</th> 
       <th th:text="#{resolution.response}">Response</th> 
       <th th:text="#{resolution.satisfactionLevel}">Satisfaction</th> 
       <th th:text="#{resolution.comment}">Comment</th> 
      </tr> 
      <tr th:each="feedback : ${feedbacks}"> 
       <td style="display:none;"><input type="hidden" name="feedbackIds" th:value="${feedback.id}" /></td> 
       <td th:text="${feedback.service.description}">Steel</td> 
       <td th:text="${feedback.description}">Problem</td> 
       <td th:text="${feedback.visits[0].date}">12/08/2015</td> 
       <td th:text="${feedback.visits[0].repr.fullName}">XYZ</td> 
       <td th:text="${feedback.receipt.resolutions[0].response}">response</td> 
       <td> 
        <div class="radio"> 
         <label><input type="radio" name="satisfaction" th:text="#{global.yes}" value="SATISFIED">Yes</input></label> 
        </div> 
        <div class="radio"> 
         <label><input type="radio" name="satisfaction" th:text="#{global.no}" value="NOT SATISFIED">No</input></label> 
        </div> 
       </td> 
       <td><textarea class="form-control" rows="2" id="comment" name="comment"></textarea></td> 
      </tr> 
     </table> 
     <div class="form-group"> 
      <button type="submit" name="addRow" th:text="#{button.submit}" 
       class="btn btn-primary btn-md">Submit</button> 
     </div> 
    </div> 
</form> 

Моя форма:

public class ReceiptForm { 
    private HashMap<Integer, String> comments; 
    private int[] feedbackIds; 
    private HashMap<Integer, String> satisfactions; 

    public HashMap<Integer, String> getComments() { 
     return comments; 
    } 

    public int[] getFeedbackIds() { 
     return feedbackIds; 
    } 

    public HashMap<Integer, String> getSatisfactions() { 
     return satisfactions; 
    } 

    public void setComments(HashMap<Integer, String> comments) { 
     this.comments = comments; 
    } 

    public void setFeedbackIds(int[] feedbackIds) { 
     this.feedbackIds = feedbackIds; 
    } 

    public void setSatisfactions(HashMap<Integer, String> satisfactions) { 
     this.satisfactions = satisfactions; 
    } 
} 

В текущем коде, входы одинаковы для всех итераций. Требование состоит в том, что входы формы satisfaction и comment будут раздельными для каждого feedback. Длина feedbacks меняется каждый раз, поэтому я не могу дать им статические имена. Как мне это сделать? Также, как я должен записывать эти данные в форме Java?

+0

Почему длина такого фактора здесь, если я могу спросить? – Vaelyr

+0

@Vaelyr Длина 'отзывов' меняется каждый раз, поэтому я не могу дать им статические имена. – khateeb

ответ

1

Пожалуйста, взгляните на раздел 7.6 Dynamic fields in the Thymeleaf + Spring tutorial. В основном вам нужно отслеживать состояние итерации. Я не знаю, что делает ваша программа, но вы должны создать beb-бланк, содержащий список обратных ссылок. Вот простой пример, который демонстрирует использования динамических полей:

Создать класс для обратной связи:

public class Feedback { 

    private Satisfaction satisfaction; 

    private String comment; 

    public Satisfaction getSatisfaction() { 
     return satisfaction; 
    } 

    public void setSatisfaction(Satisfaction satisfaction) { 
     this.satisfaction = satisfaction; 
    } 

    public String getComment() { 
     return comment; 
    } 

    public void setComment(String comment) { 
     this.comment = comment; 
    } 

    @Override 
    public String toString() { 
     return "Feedback[satisfaction=" + satisfaction.name() + ", comment=" + comment + "]"; 
    } 

    public static enum Satisfaction { 

     SATISFIED, NOT_SATISFIED 

    } 

} 

Создать класс, который содержит список обратных связей:

public class Receipt { 

    private List<Feedback> feedbacks = new ArrayList<>(); 

    public List<Feedback> getFeedbacks() { 
     return feedbacks; 
    } 

    public void setFeedbacks(List<Feedback> feedbacks) { 
     this.feedbacks = feedbacks; 
    } 

    @Override 
    public String toString() { 
     return "Receipt[feedbacks=" + feedbacks + "]"; 
    } 

} 

Создать контроллер, который помещает форму-бэк-компонент в модель:

@Controller 
public class MyController { 

    @RequestMapping("/") 
    public String showForm(final Model model) { 
     final Receipt receipt = new Receipt(); 
     final Random rand = new Random(); 
     final int feedbackCount = rand.nextInt(20) + 1; 

     for (int i = 0; i < feedbackCount; i++) { 
      final Feedback feedback = new Feedback(); 

      feedback.setSatisfaction(rand.nextBoolean() ? SATISFIED : NOT_SATISFIED); 
      feedback.setComment("Some comment."); 
      receipt.getFeedbacks().add(feedback); 
     } 

     model.addAttribute("receipt", receipt); 

     return "form"; 
    } 

    @RequestMapping(value = "/", method = RequestMethod.POST) 
    public String printSubmittedData(final @ModelAttribute Receipt receipt) { 
     System.out.println(receipt); 

     return "redirect:/"; 
    } 

} 

Создайте шаблон, который показывает форму:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> 
<head> 
</head> 
<body> 
<form action="#" th:action="@{/}" th:object="${receipt}" method="post"> 
    <table> 
    <tr th:each="feedback, feedbackStat : *{feedbacks}"> 
     <td> 
     <div class="radio"> 
      <label> 
      <input type="radio" th:field="*{feedbacks[__${feedbackStat.index}__].satisfaction}" value="SATISFIED" /> 
      Yes 
      </label> 
     </div> 
     <div class="radio"> 
      <label> 
      <input type="radio" th:field="*{feedbacks[__${feedbackStat.index}__].satisfaction}" value="NOT_SATISFIED" /> 
      No 
      </label> 
     </div> 
     </td> 
     <td> 
     <textarea rows="2" th:field="*{feedbacks[__${feedbackStat.index}__].comment}"></textarea> 
     </td> 
    </tr> 
    </table> 
    <button type="submit">Submit</button> 
</form> 
</body> 
</html> 

Контроллер создает случайное число обратных связей, чтобы продемонстрировать динамический рендеринг полей.

+0

Как захватить эти данные в форме Java? – khateeb

+0

Вам нужен бэк-бланк, который имеет список отзывов в качестве участника. – stevecross

+0

Не могли бы вы также дать код для этого? – khateeb

Смежные вопросы