I have issues in binding enum values in hidden fields with spring mvc.
The scenario is the following: I have a form with a list of documents which are characterized by a type.
My form class is (please note how the constructor is made. It fills the documents list with empty documents whose type is taken from the DocumentType enumeration):
public class Form {
private List<Document> documents = new ArrayList<Document>();
//while creating this class, I instantiate a number
//of empty documents with a certain type attribute
public Form() {
super();
for(DocumentType type : DocumentType.values())
{
Document document = new Document();
document.setType(type);
documents.add(document);
}
}
}
my document class is:
public class Document{
private DocumentType type;
private String expirationDate
private URL link
//getters & setters
}
while DocumentType is an ordinary enumeration
public enum DocumentType {
TYPE_A("type a"),
TYPE_B("type b"),
TYPE_C("type c");
private String literal;
public String getLiteral() {
return literal;
}
private StateDocumentType(String literal) {
this.literal = literal;
}
}
I want to display a form of this kind (the rounded boxes are form fields):
so, in order to update the right document with the proper link and expiration date, I want to use an hidden field associated to every form input row.
So my jsp is the following:
<form:form role="form" id="form" commandName="stateForm" action="${formUrl }">
<c:forEach items="${form.documents }" var="document" varStatus="vs">
<div id="doc_${document.type }>
<label>${document.type.literal }</label>
<div class="input-group">
<form:hidden path="documents[${vs.index }].type"/>
<form:input type="text" path="documents[${vs.index }].link"/>
</div>
</div>
<!-- omitted the exp. date part -->
</c:forEach>
</form:form>
here's the problem: when the html page is requested and rendered, the hidden field "value" attribute is just empty, while I expected it is valorized with the proper enum value. Please note that the parent <div> id is properly valorized. I really don't know why this doesn't work.
Related
I have an application in which I am trying to assign users to a conference. When submitted though, it passes as a string and I receive an error for type mismatch.
My controller methods:
#GetMapping(path = "/assign/{id}")
public String showStudentAssignForm(#PathVariable(name = "id") Long id, Model model){
Optional<Conference> conference = conferenceService.findById(id);
List<User> userList = userService.findAllByRoles("ROLE_STUDENT");
model.addAttribute("userList", userList);
model.addAttribute("conference", conference.get());
return "assignStudent";
}
#PostMapping(path = "/assign/save")
public String saveAssignedUsers(ConferenceDto conference){
conferenceService.updateConference(conference);
return "redirect:/teacher/configure";
}
In my controllerDto I have:
private Collection<User> students;
In the html I have:
<div class="form-group row">
<label class="col-form-label col-sm-4">Users: </label>
<div class="col-sm-8 text-left">
<th:block th:each="user : ${userList}">
<div>
<input type="checkbox" th:field="*{students}" th:text="${user.name}" th:value="${user}" class="m-2" />
</div>
</th:block>
</div>
</div>
It's supposed to pass selected users and store it as a collection although they are passed as string. I get the following error:
Field error in object 'conferenceDto' on field 'students': rejected value [Bill Gates,Test McTest]; codes [typeMismatch.conferenceDto.students,typeMismatch.students,typeMismatch.java.util.Collection,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [conferenceDto.students,students]; arguments []; default message [students]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.Collection' for property 'students'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.lukas.ramonas.cms.Model.User' for property 'students[0]': no matching editors or conversion strategy found]]
Any suggestions how I can solve this issue? Am I supposed to make a converter (if so how can I implement it in my controller?) or can I go around this another way? Any tips are appreciated!
So the problem seemed to revolve around having the string mismatch with collection and/or user. I solved this issue by changing private Collection<User> students; to private Collection<String> students; in my conferenceDto and then when saving in my ConferenceService class I add to the conference(model object, not the Dto) the list of users which I find with findByName or findById from the string in the conferenceDto.
I need choose values from one array and assign it to other array. Using Spring Thymeleaf. No idea how retrieve these choosed values.
My classes:
#Entity
public class Collaborator {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size (min=3, max=32)
private String name;
#NotNull
#ManyToOne (cascade = CascadeType.ALL)
private Role role;
public Collaborator() {}...
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 3, max = 99)
private String name;
public Role() {}....
My controllers:
#RequestMapping("/project_collaborators/{projectId}")
public String projectCollaborators(#PathVariable Long projectId, Model model) {
Project project = mProjectService.findById(projectId);
List<Collaborator> allCollaborators = mCollaboratorService.findAll();
List<Collaborator> assignments = new ArrayList<>();
if (project.getRolesNeeded()!=null) {
for (int i=0;i<project.getRolesNeeded().size();i++) {
assignments.add(new Collaborator("Unassigned", project.getRolesNeeded().get(i)));
assignments.get(i).setId((long) 0);
}
}
model.addAttribute("assignments", assignments);
model.addAttribute("allCollaborators", allCollaborators);
model.addAttribute("project", project);
return "project_collaborators";
}
#RequestMapping(value = "/project_collaborators/{projectId}", method = RequestMethod.POST)
public String projectCollaboratorsPost(#ModelAttribute Project project, #PathVariable Long projectId, Model model) {
Project p = mProjectService.findById(projectId);
//mProjectService.save(project);
return "redirect:/project_detail/{projectId}";
}
And template:
<form th:action="#{'/project_collaborators/' + ${project.id}}" method="post" th:object="${project}">
<label th:text="'Edit Collaborators: ' + ${project.name}">Edit Collaborators: Website Project</label>
<ul class="checkbox-list">
<li th:each="a : ${assignments}">
<span th:text="${a.role.name}" class="primary">Developer</span>
<div class="custom-select">
<span class="dropdown-arrow"></span>
<select th:field="${a.id}">
<option th:each="collaborator : ${allCollaborators}" th:value="${collaborator.id}" th:text="${collaborator.name}">Michael Pemulis</option>
</select>
</div>
</li>
</ul>
<div class="actions">
<input type="submit" value="Save" class="button"/>
Cancel
</div>
</form>
As you can see I want to let user choose for each role (roleNeeded) any collaborator from (allCollaborators) and keep that assigns in List (assignments).
And I get error message:
ava.lang.IllegalStateException: Neither BindingResult nor plain target
object for bean name 'a' available as request attribute
So question is: how to solve it, assign values from one array to another in template and retrieve that values in my controller.
The cause of the exception
The IllegalStateException you are getting is because th:field="${a.id}" in your select element must be related to the form th:object="${project}" element; the th:field attribute must refer to an actual field in the project instance (also you need to write th:field="*{fieldName}"). That should fix the exception you are getting, but will not solve your entire problem as the second part of it is related to how to make the values get into your controller, which I will explain next.
Sending the values to your controller
To get the values into your controller you will need to make a few changes. As I don't really know the code of your Project class, I will change a few things so you will be able to figure it out how to adapt this simple example to your particular case.
First, I understand you want to make a relation like the following in your form:
Role1 => CollaboratorA
Role2 => CollaboratorB
Your controller needs to receive a list and in order to receive this information we need two classes:
The class which will be storing the individual element data, mapping a role id with the collaborator id:
public class RoleCollaborator {
private Long roleId;
private Long collaboratorId;
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getCollaboratorId() {
return collaboratorId;
}
public void setCollaboratorId(Long collaboratorId) {
this.collaboratorId = collaboratorId;
}
}
A wrapper class to store a list of individual mappings:
public class RolesCollaborators {
private List<RoleCollaborator> rolesCollaborators;
public List<RoleCollaborator> getRolesCollaborators() {
return rolesCollaborators;
}
public void setRolesCollaborators(List<RoleCollaborator> rolesCollaborators) {
this.rolesCollaborators = rolesCollaborators;
}
}
The next thing to do is change your controllers where you have two methods, one that handles GET requests and another one which handles the POST requests and so, receives your form data.
In the GET one:
public String projectCollaborators(#PathVariable Long projectId, Model model) {
(... your code ...)
model.addAttribute("project", project);
// Add the next line to add the "rolesCollaborators" instance
model.addAttribute("rolesCollaborators", new RolesCollaborators());
return "project_collaborators";
}
As you can see, we added a line that will be used by the thymeleaf template. Right now is a wrapper of an empty list of roles and collaborators, but you can add values if you need to edit existing mappings instead of adding new ones.
In the POST one:
// We changed the #ModelAttribute from Project to RolesCollaborators
public String projectCollaboratorsPost(#ModelAttribute RolesCollaborators rolesCollaborators, #PathVariable Long projectId, Model model) {
(... your code ...)
}
At this point, your controller is prepared to receive the information sent from your form, that we also need to modify.
<form th:action="#{'/project_collaborators/' + ${project.id}}" method="post" th:object="${rolesCollaborators}">
<label th:text="'Edit Collaborators: ' + ${project.name}">Edit Collaborators: Website Project</label>
<ul class="checkbox-list">
<li th:each="a, stat : ${assignments}">
<span th:text="${a.role.name}" class="primary">Developer</span>
<div class="custom-select">
<input type="hidden" th:id="rolesCollaborators[__${stat.index}__].roleId" th:name="rolesCollaborators[__${stat.index}__].roleId" th:value="${a.role.id}" />
<span class="dropdown-arrow"></span>
<select th:field="*{rolesCollaborators[__${stat.index}__].collaboratorId}">
<option th:each="collaborator : ${allCollaborators}" th:value="${collaborator.id}" th:text="${collaborator.name}">Michael Pemulis</option>
</select>
</div>
</li>
</ul>
<div class="actions">
<input type="submit" value="Save" class="button"/>
Cancel
</div>
</form>
Here there are a few changes:
As I pointed out in The cause of the exception you need to change th:object="${project}" to th:object="${rolesCollaborators}", as rolesCollaborator is the instance name from where you will receive the values from your GET controller method and where you will be sending the values to your POST controller method.
I added a hidden input; this input will store the role id that will be send in association to the collaborator id the user picks from the interface using the select element. Take a look at the syntax used.
I changed the th:field value of your select element to refer to a field in the rollesCollaborators object we use in th:object="${rolesCollaborators}" form attribute. This will set the value of the collaborator in the RoleCollaborator element of the RolesCollaborators wrapped list.
With these changes your code will work. Of course, you can improve it with some other modifications, but I tried to not introduce more modifications to focus on your problem.
I'm trying to create a list of objects from form inputs. The objects are the same but their values may differ, it's essentially a menu.
I'm still getting to grips with Spring/Thymeleaf which is adding some level of complexity to what feels like a simple task.
I've a class for the menu, a simple POJO, there is then a list of these defined as a data member in the bean itself:
private ArrayList<GuestMenuOptions> guestMenus;
I've read many posts, tried many things and am on the verge of softly resting my head against the table.
I've had several errors, most of which either tell me that the list cannot be found or that the list is empty - it's currently in stable condition where the list, no matter what I try, will not be populated, even when I load in default values...unfortunately my debugger has died which is not helping.
Any help is appreciated. thank you
EntryController:
#RequestMapping(method=RequestMethod.GET, value="/")
public String indexPage(Model model) {
model.addAttribute("childMenuOptions", generateChildMenus());
//not sure if this is neccesary...
ArrayList<GuestMenuOptions>guestMenus = new ArrayList<>();
GuestMenuOptions ad1 = new GuestMenuOptions();
GuestMenuOptions ad2 = new GuestMenuOptions();
guestMenus.add(ad1);
guestMenus.add(ad2);
GuestContactBean ctb = new GuestContactBean();
ctb.setGuestMenus(guestMenus);
model.addAttribute("guestContactBean", ctb);
model.addAttribute("formBackingBean", new FormBackingBean());
return "index";
}
Form:
<form modelAttribute="guestBean" class="contact_form" name="rsvp" role="form" th:object="${formBackingBean}" th:action="#{/sendRsvp}" method="post">
<div class="row">
<div class="form-group">
<select name="ad1Starter" id="starterMealAdult1">
<option value="!!!">-Starter-</option>
<option th:field="${guestContactBean.guestMenus[0].starter}" th:each="entry : ${adultMenuOptions.get('starter').entrySet()}" th:value="${entry.key}" th:text="${entry.value}">
</option>
</select>
</div>
<input type="submit"guest name="submit" class="btn default-btn btn-block" value="Send RSVP">
RequestController:
#RequestMapping(value = "/sendRsvp", method = RequestMethod.POST)
public String sendRsvp(#ModelAttribute("guestContactBean") GuestContactBean guestContactBean,
#ModelAttribute("guestMenus") ArrayList<GuestMenuOptions>menus,
BindingResult result) throws MessagingException {
smtpMailSender.send(guestContactBean);
return "thanksMessage";
}
Beans:
FormBacking is POJO with no reference to the menus at all.
GuestMenuOptions is the same with just starter, desert members
guestContactbean has not much more going on, basic fields with the addition of the list of GuestMenuOptions
private String numberOfAdults;
private String eventAttending;
private ArrayList<GuestMenuOptions> guestMenus;
public ArrayList<GuestMenuOptions> getGuestMenus() {
return guestMenus;
}
EDIT:
The field that populates the drop downs in working fine, it's declared as private Map<String, Map<String, String>> adultMenuOptions;
private Map<String, Map<String, String>> childMenuOptions;
they are then built in the controller so that each may have several options under 'starter', 'main' and desert' for example:
starter.put("salmon", "Smoked Salmon");
starter.put("pate", "Chicken Liver Pate");
this is then populating both the value and text of the dropdown.
If I could save the state of this Map and pass it back to the controller instead, that would also be fine but I wasn't able to why then spawned the creation of the there wrapper list.
Please revisit http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dropdownlist-selectors. It should be as simple as
class Animal {
int id;
String name;
}
then in your template:
<select th:field="*{animalId}">
<option th:each="animal : ${animals}"
th:value="${animal.id}"
th:text="${animal.name}">Wireframe</option>
</select>
I think your code is all over the place and you're mixing up menu selection with menu item types.
I'm new to Spring and I would like to get id and value of selected item of a dropdown. Here is a simple example
class MaritalStatus{
private int id;
private String status;
}
class regForm{
private MaritalStatus maritalStatus;
...
}
//Simple Controller to fill the list
#RequestMapping(value = "/save")
public String init(Model model){
List<MaritalStatus> maritalList = new ArrayList<MaritalStatus>();
maritalStatus.setId(1)
maritalStatus.setStatus("Married")
maritalList.add(maritalStatus);// add all status to the list....
model.addAttribute("maritalList",maritalList);
...
}
jsp page
<form:form commandName="regForm" action="save">
<form:select path="maritalStatus.id">
<form:options items="${maritalList}" itemValue="id" itemLabel="status" />
</form:select>
</form:form>
This is where I want to get selected item id and value (1 and Married)
#RequestMapping(value = "/save")
public String save(Model model,#ModelAttribute("regForm") RegForm regForm){
// here I want to get selected item Id and Status(Label)
//regFrom.getMaritalStatus().getId() and regFrom.getMaritalStatus().getStatus()
}
You can achieve it at least in 2 ways:
Send only the id of the selected MaritalStatus (you actually do it in your jsp), bind it directly to regForm.maritalStatusId and then (when you need it) get the MaritalStatus from the maritalList by the selected id (you have to keep the maritalList or create it somewhere, you do it anyway)
Bind your select directly to regForm.maritalStatus <form:select path="maritalStatus"> and write a specialized formatter that can convert from id to MaritalStatus object and vice versa. You'll find more information how to do it here: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/html/validation.html#format
[You could also send the id of the selected field and additionally its value in the hidden field and then try to build from those the MaritalStatus on the server side, but it is not elegant.]
You can get status by one hidden variable in jsp and a javascript function.
function changeStatus() {
var statusSelected = document.getElementById("maritalStatus");
var option = cookerModeIdSelected.options[statusSelected.selectedIndex];
var selectedValue = option.getAttribute("data-status");
document.getElementById("regForm").submit();
}
<form:form commandName="regForm" action="save">
<form:hidden id="maritalStatusValue" path="maritalStatusValue"/>
<form:select path="maritalStatus.id" id="maritalStatus">
<form:options items="${maritalList}" itemValue="id" itemLabel="status" data-status="${status}"/>
</form:select>
</form:form>
If a HTML form contains multiple input fields:
<form>
<input id="in1" type="text" value="one">
<input id="in2" type="text" value="two">
<input id="in3" type="text" value="three">
</form>
and is passed to a Spring controller as a serialized form like this:
new Ajax.Request('/doajax',
{asynchronous:true, evalScripts:true,
parameters: $('ajax_form').serialize(true)});
what Java type would be needed to read the serialized ajax_form in a Spring 3 controller?
#RequestMapping("/doajax")
#ResponseBody
public String doAjax(#RequestParam <?Type> ajaxForm
{
// do something
}
First of all, you use form fields without names, so serialize() actually produces an empty result. Add names:
<form>
<input name = "in1" id="in1" type="text" value="one">
<input name = "in2" id="in2" type="text" value="two">
<input name = "in3" id="in3" type="text" value="three">
</form>
I guess you use Prototype, so parameters: $('ajax_form').serialize(true) produces a URL-encoded representation of the form (and also you don't need true here, it adds unnecessary conversion). Since #RequestParam can't bind complex types, you can bind fields as separate parameters:
public String doAjax(#RequestParam("in1") String in1,
#RequestParam("in2") String in2, #RequestParam("in2") String in2)
Also you can create a class to hold form data and pass it as a model attribute:
public class AjaxForm {
private String in1;
private String in2;
private String in3;
... getters, setters ...
}
-
public String doAjax(AjaxForm form)