Path attribute in form:select - spring 2.5 JSP - spring

I've been put on the task of learning spring (2.5), and I've got into a problem using the attribute where, when the form is loaded, I wont get any pre-selected values. So the situation is as follows:
In my system I have Companies, Customers and Users. Customer extends Company, and a Company can have a List of Users (the getMethod is public so hence Customer also have a List of Users).
So this is how the form select looks in my .JSP:
<form:select multiple="true" id="selectAccountManager" path="${customer.users}" cssClass="input select_img" >
<c:forEach items="${customerUsers}" var="user" >
<form:option value="${user.id}
<c:out value="${user.displayName}" />
</form:option
</c:forEach>
</form:select>
Right now, I get an error on the path="${customer.users}". If I use path="users" my system works, but then I wont get any of the values within the form as "pre-selected" when the page loads. I've tried with path="customer.users" but when I do this I get a referenceError in js-console.
The .JSP is mapped to an EditCustomerController where customerUsers is put into a map by
map.put("customerUsers", UserControlHelper.getAllUsers());
So I guess this is where the problem lies as I always get all users from the system?
TL;DR: How do I set selected values on a form where I load the items from one class, and want the select-filter to come from another?

(First of all, Spring 2.5 is old and I suggest you to use 3.2.x or even 4.0.x)
To pre-select option you should set appropriate field on the model and Spring will pre-select it automagically. Like that:
<form:form method="post" modelAttribute="myForm">
<form:select multiple="true" path="users">
<form:options items="${customerUsers}" itemLabel="displayName" itemValue="id" />
</form:select>
</form:form>
And in the controller:
User defaultUser = new User(1, "DEFAULT");
MyForm myForm = new myForm();
myForm.getUsers().add(defaultUser);
model.addAttribute("myForm", myForm);

So I found out what the problem was.
When I created my map I only put the users in there. What the User-object actually was mapped upon was the id of the user (something I retrieved through ${user.id} as can be seen in the originalpost. What I had to do was to create the path in a correct way as such:
Controller - java:
Map<Int,String> users = new HashMap<Int,String>();
for(User user: UserControlHelper.getAllUsers()){
users.add(user.getId(), user.getDisplayName())
}
model.put("customerUsers", users);
and my jsp:
<form:select path="users" items="${customerUsers}"></form:select>

Related

Spring Form:Select selected value

I know this has been asked before but the solutions provided doesn't seem to work on my end.
I'm currently developing a web application and I'm currently working on the user profile page. What I'm doing is that when the user visits his/her profile, he/she will be able to manage his/her profile.
I have a spring form:select box which populates a List of RolesObject and a List of GroupsObject passed from the controller. The object consists of an id and name fields. What I want is when the form:select loads, it will select the present role id and group id of the user from the list.
controller
public ModelAndView viewProfile(parameters) {
ModelAndView mav = new ModelAndView();
mav.setViewName("viewProfile");
...
List<RolesObject> roles = rolesService.getRolesList();
List<GroupsObject> groups = groupsService.getGroupsList();
Map<String, List> map = new HashMap<String, List>();
map.put("roles", roles);
map.put("groups", groups);
mav.addObject("map", map);
return mav;
view
<form:select path="role_id" id="role_id" cssClass="form-control" cssStyle="width: 100%;" value="${current.getRole_id()}" required="required">
<c:forEach var="role" items="${map.roles}">
<form:option value="${role.getId()}" label="${role.getName()}" />
</c:forEach>
</form:select>
<form:select path="group_id" id="group_id" cssClass="form-control" cssStyle="width: 100%;" value="${current.getGroup_id()}" required="required">
<c:forEach var="group" items="${map.groups}">
<form:option value="${group.getId()}" label="${group.getName()}" />
</c:forEach>
</form:select>
My problem is the list populates but it does not select a default value.
Let's say my role values are
value=1, label=role_1
value=2, label=role_2
and the user's current role is role_2 which has an id of 2, when the select form loads, it does not automatically load role_2 but instead still shows role_1 as the selected value
For preselection of the option you need to set the role_id and group_id in the controller and set it as the modelattribute of the form object on page.

java springframework <select> tag

I am struggling with "SELECT/OPTIONS" tag. I have 2 ArrayList<<String>>: "pNames" and "pIds". Form should display "pNames", while the values returned to controller should be "pIds". From my spring controller I am passing the following 2 ArrayLists. How do I implement this in Spring MVC?
ArrayList<String> pIds = pps.getPIds();
ArrayList<String> pNames = pps.getPNames();
model.addAttribute("pIds", pIds);
model.addAttribute("pNames", pNames);
<form:select id="pps" name="pps" path="pIds" multiple="multiple">
<form:options items="${pIds}" itemValue="${pNames}" itemLabel="${pNames}"/>
</form:select>
Above code is not working.
You need to convert your Lists to a Map<String, String>. Then you can add the map to your model and you only need to do:
<form:select path="pIds">
<form:options items="${mapName}" />
</form:select>
For more information, please checkout this question: Use <form:select> tag with a map

Checkboxes tag spring mvc and binding

I have checkboxes tag in my web application with spring mvc. Checkboxes are created from a map in controller like this:
Map demOrgs = createMap();
model.addAttribute("demOrgs", demOrgs); // example : (1, my-description)
1 --> will be value of checkbox
my-description --> will be label of checkbox
In my jsp :
<form:form commandName="myBean" method="POST" >
<form:checkboxes items="${demOrgs}" path="demOrg" element='div class="checkboxes"' />
</form:form>
My bean has only one field :
String demOrg;
When I send the form demOrg attribute has the value of checkboxes clicked, for example: (1,5,8)
I store myBean in session, when I go to the next step in my application. But when I return, I want the checkboxes were checked, still checked and isn't that way.
When the bind value of checkbox is a boolean value, allways work but I'm binding a custom value :
<input id="demOrg1" type="checkbox" value="2" name="demOrg">
<label for="demOrg1">My label description</label>
<input id="demOrg2" type="checkbox" value="3" name="demOrg">
<label for="demOrg2">My label description 2</label>
.....
Does anyone know how to do this?
thanks to all!!
What does the signature of your controller method look like? Are you including myBean as a method signature argument, annotated with #ModelAttribute ?
Something like:
#RequestMapping(......)
public String myController (#ModelAttribute MyBeanType myBean, Model model) {
Map demOrgs = createMap();
model.addAttribute("demOrgs", demOrgs);
model.addAttribute(myBean);
}
Optionally you can annotate the method parameter with #Valid as well if you are using JSR-303 bean validation .
I think the trick is to make sure your demOrg property is actually a collection. Check out the
checkbox reference here. In particular, the text that says:
Typically the bound property is a collection so it can hold multiple values selected by the user.
Though "myBean" is stored in the session, isn't it reloaded again from the database when the controller is ran?

object references an unsaved transient instance, Error only when trying to save with empty value

I have an object EvalQuestionType with a one-to-many relationship to another object EvalSelectGroup. I save the relationship in a spring form like so:
<tr>
<th><sf:label path="evalSelectGroup.id">Select Group</sf:label>
<td><sf:select path="evalSelectGroup.id">
<sf:option value="">None</sf:option>
<sf:options items="${selectGroups}" itemLabel="name" itemValue="id" />
</sf:select>
<br />
<sf:errors path="evalSelectGroup.id" cssClass="error" /></td>
</tr>
It works fine if I select an option, but if I try to save with None selected (empty) I get the transient instance error. The value can be null (in the db and my hibernate mapping file). Is there a special way to format empty values in a Spring form select?
Spring 3.2.1
Hibernate 3.6
This may not be the best or right way to do it, but in the controller if I take the EvalQuestionType object passed by the form and set the evalSelectGroup object to null it works fine.
//if none selected in form
if(questionType.getEvalSelectGroup().getId() == null){
questionType.setEvalSelectGroup(null);
}

Using Beans to populate/retrieve view

I'm new to Spring and little confused of how to use beans for populating and retrieving values to/from the view.
Here is what I'm doing now.
In the controller I'm initializing two beans xxxMain.java and xxxView.java. I'm using xxxMain.java to retrieve values FROM the view and xxxView.java for pre-populating the view.
Here is my controller
#RequestMapping(value = "accounting", method = RequestMethod.GET)
public String showPage( Model model) {
XXXMain xxxMain = new XXXMain();
XXXView xxxView = new XXXView();
service.loadXXXForm(xxxMain, xxxView);
model.addAttribute("xxxMain", xxxMain);
model.addAttribute("xxxView", xxxView);
return "admin/xxx";
}
So as I'm using the xxxMain.java for retrieving I'm coding the jsp like this.
<form:form modelAttribute="XXXMain" method="post" action="/app/home/save">
</form:form>
also I'm using Spring tags, like
<form:input path="name" size="15"/>
Now, when the fields in the view are empty, all is fine, but when I have to pre-populate the fields, I'm not sure what approach to take as
<form:input path="name" size="15"/>
does not has a value attribute to populate the field. So what I have done is populate the XXXMain.java class along with the XXXView.java class with the default values, as you can see in the controller code snippet. That way values are pre-populated when view is first loaded. But I'm not sure if I'm doing the right thing by populating the xxxMain.java file which in fact should only contain the user entered values.
How can I improve this design?
Thanks a lot.
Ravi
Here is an example I wrote which might help steer you right.

Resources