Based on this code .

What is my problem - when editing any already created object - the fields are not automatically filled. With the example on the githaba, everything is in order - the fields are filled.

Next is my code:

@Component @Entity @Table(name = "rating", catalog = "school") public class Rating { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ratingId", unique = true, nullable = false) int rt_id; @Temporal(TemporalType.DATE) @DateTimeFormat(pattern="dd.MM.yyyy") @Column(name = "ratingDate", nullable = false) Date rt_Date; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "chId", nullable = false) Children children; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "subjectId", nullable = false) Subject subject; @Column(name = "evaluation", nullable = false) int evaluation; *сеттеры, геттеры и конструктор без параметров* 

Controller (for now):

 @Controller public class RatingController { private SubjectService subjectService; @Autowired(required = true) public void setSubjectService(SubjectService subjectService) { this.subjectService = subjectService; } private RatingService ratingService; @Autowired(required = true) public void setRatingService(RatingService ratingService) { this.ratingService = ratingService; } private ChildrenService childrenService; @Autowired(required = true) public void setChildrenService(ChildrenService childrenService) { this.childrenService = childrenService; } @ModelAttribute("subjects") public List<Subject> getAllSubjects() { return subjectService.listSubjects(); } @ModelAttribute("childrens") public List<Children> getAllChildrens() { return childrenService.listChildrens(); } @ModelAttribute("listRatings") public List<Rating> getAllRatings() { return this.ratingService.listRatings(); } @RequestMapping(value = "ratings", method = RequestMethod.GET) public String listRatings(Model model) { model.addAttribute("rating", new Rating()); return "ratings"; } @RequestMapping(value = "/ratings/add", method = RequestMethod.POST) public String addRating(@ModelAttribute("rating") Rating rating) { if (rating.getRt_id() == 0) { this.ratingService.addRating(rating); }else { this.ratingService.updateRating(rating); } return "redirect:/ratings"; } @RequestMapping("/ratings/edit/{id}") public String updateRating(@PathVariable("id") int id, Model model) { Rating rating = (Rating) this.ratingService.getRatingById(id); model.addAttribute("rating", rating); return "ratings"; } @RequestMapping("/ratings/delete/{id}") public String removeRating(@PathVariable("id") int id) { this.ratingService.removeRating(id); return "redirect:/ratings"; } @InitBinder public void initBinder(ServletRequestDataBinder binder) { binder.registerCustomEditor(Children.class, "children", new PropertyEditorSupport() { public void setAsText(String text) { Integer id = Integer.parseInt(text); Children children = (Children) childrenService.getChildrenById(id); setValue(children); } public String getAsText() { Object value = getValue(); if (value != null) { Children children = (Children) value; return children.getCh_name(); } return null; } }); binder.registerCustomEditor(Subject.class, "subject", new PropertyEditorSupport() { public void setAsText(String text) { Integer sub_id = Integer.parseInt(text); Subject subject = (Subject) subjectService.getSubjectById(sub_id); setValue(subject); } public String getAsText() { Object value = getValue(); if (value != null) { Subject subject = (Subject) value; return subject.getSub_name(); } return null; } }); } @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, true)); } } 

And JSP:

 <%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ page session="false" %> <html> <head> <title>Список оценок</title> </head> <body> <h1>Список оценок</h1> <c:if test="${!empty listRatings}"> <table class="tg"> <tr> <th width = "80">ID</th> <th width = "120">Дата</th> <th width = "120">Ученик</th> <th width = "120">Предмет</th> <th width = "120">Оценка</th> </tr> <c:forEach items="${listRatings}" var="rating"> <tr> <th>${rating.rt_id}</th> <th><fmt:formatDate pattern="dd/MM/yyyy" value="${rating.rt_Date}" /></th> <th>${rating.children.ch_name}&nbsp ${rating.children.ch_surname}</th> <th>${rating.subject.sub_name}</th> <th>${rating.evaluation}</th> <td width = "120"><a href="<c:url value="/ratings/edit/${rating.rt_id}"/>">Редактировать</a></td> <td><a href="<c:url value="/ratings/delete/${rating.rt_id}"/>">Удалить</a></td> </tr> </c:forEach> </table> </c:if> <h1>Добавить оценку</h1> <c:url var="addAction" value="/ratings/add"/> <form:form action="${addAction}" commandName="rating"> <table> <c:if test="${!empty rating.rt_id}"> <tr> <td> <form:label path="rt_id"> <spring:message text="ID"/> </form:label> </td> <td> <form:input path="rt_id" readonly="true" disabled="true"/> <form:hidden path="rt_id"/> </td> </tr> </c:if> <tr> <td> <form:label path="rt_Date"> <spring:message text="Дата оценки"/> </form:label> </td> <td> <form:input path="rt_Date" placeholder="День/Месяц/Год"/> </td> </tr> <tr> <td>Учащийся</td> <td><form:select path="children" items="${childrens}" itemLabel="ch_name" itemValue="ch_id"/></td> <td><form:errors path="children"/></td> </tr> <tr> <td>Предмет</td> <td><form:select path="subject" items="${subjects}" selected="true" itemLabel="sub_name" itemValue="sub_id"/></td> <td><form:errors path="subject" cssClass="error"/></td> </tr> <tr> <td> <form:label path="evaluation"> <spring:message text="Оценка"/> </form:label> </td> <td> <form:select path="evaluation"> <option value="0">Отсутствовал</option> <option value="1">Присутствовал</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </form:select> </td> </tr> <tr> <td colspan="2"> <c:if test="${!empty rating.rt_Date}"> <input type="submit" value="<spring:message text="Edit Rating"/>"/> </c:if> <c:if test="${empty rating.rt_Date}"> <input type="submit" value="<spring:message text="Add Rating"/>"/> </c:if> </td> </tr> </table> </form:form> </body> </html> 

Example What did I miss in understanding this mechanism (autofilling a form when editing)? Thank!

  • What fields you do not appear, and what are displayed? - MrFylypenko
  • I gave a link to git from above, in which if I clicked "edit" (Task object), then this Task object will first have filled out all its fields and I don’t need to "select / drive in" again (I might have wanted change only one field, suppose). I don’t have such a thing, in the screenshot that you see, I clicked on "Jolie" to edit - but only the time was automatically filled, and the rest of the fields (which are objects) didn’t get out automatically and they had to be filled all over again. Apparently I did not understand something? Thank. - CheshireK
  • I would like to clarify with you, when you click on edit, the ID field is filled with the correct ID, and with the other fields not filled? - MrFylypenko
  • Yes, ID and Date are correct, the rest (all you need to choose from the lists) is wrong. - CheshireK
  • Check your method this.ratingService.getRatingById(id); , does it really return the data you need with loaded entities subject and children (Output to the console). I would redo the evaluation field by adding its values ​​to the controller, like subject . - MrFylypenko 1:59 pm

1 answer 1

In the above github project, initBinder is used, which substitutes the desired value in the field. You can use it in the future.

To correctly display form:select you need to specify not path="subject" , but path="subject.sub_id" , i.e. The id to insert into itemValue="sub_id" . Code example:

 <h1>Добавить оценку</h1> <form:form action="test" commandName="rating"> <table> <tr> <td> ID </td> <td> <form:input path="rt_id" readonly="true" disabled="true"/> </td> </tr> <tr> <td> subject.sub_name </td> <td> <form:input path="subject.sub_name" readonly="true" disabled="true"/> </td> </tr> <tr> <td>Предмет</td> <td><form:select path="subject.sub_id" items="${subjects}" itemLabel="sub_name" itemValue="sub_id"/> </td> <td></td> </tr> </table> </form:form> 

In the controller:

 @RequestMapping("/rating") public String updateRating( Model model) { Rating rating = new Rating(); rating.setRt_id(1); Subject subject = new Subject(); subject.setSub_id(3); subject.setSub_name("CCCC"); rating.setSubject(subject); model.addAttribute("rating", rating); return "test"; } @ModelAttribute("subjects") public List<Subject> getAllSubjects() { List<Subject>subjects = new ArrayList<Subject>(); Subject subject = new Subject(); subject.setSub_id(1); subject.setSub_name("AAAA"); subjects.add(subject); subject = new Subject(); subject.setSub_id(2); subject.setSub_name("BBBB"); subjects.add(subject); subject = new Subject(); subject.setSub_id(3); subject.setSub_name("CCCC"); subjects.add(subject); return subjects; } class Subject { private int sub_id; private String sub_name; //get,set } class Rating { private int rt_id; private Subject subject; //get,set } 
  • Immediately earned! Thank you so much for your time and solution! Good luck! - CheshireK