Submitting spring form on select change event passing parameter - spring

I an using Spring 3.x and attempting to submit a form when the value of a drop down changes - in such a way that the controller can properly determine which method to call:
<form:form modelAttribute="myContainer" action="/credits/processAssignment.ntwx"
method="post" name="assignmentsForm">
<form:select path="currentCreditId" width="400" onchange="submit()">
<c:forEach items="${creditIds}" var="creditId">
<form:option value="${creditId}" >
</c:forEach>
</form:option>
</form:select>
...other controls and submit buttons
</form:form>
When the value of the select/drop-down changes, I would like to have it call this method in the controller:
#RequestMapping(value = "/credits/processAssignment.ntwx", method = RequestMethod.POST,
params="creditIdChanged" )
public ModelAndView creditIdChanged( HttpServletRequest request, HttpServletResponse
response, #ModelAttribute("myContainer") MyContainer myContainer, ModelMap model)
I think the key to this is figuring out how to pass the param 'creditIdChanged' from the dropdown. I have a few submit buttons on the page that pass the param by their name attribute:
<input type="submit" name="addRow" value="Add Row" class="button" />
This will pass the param 'addRow', so it's easy to map this submit to a controller method. Using the name='creditIdChanged' or id='creditIdChanged' of the form:select does not pass creditIdChanged as the parameter.
Any Suggestions?

Related

Why do I lose information after submit a form with Spring MVC?

As I say int the title I loose information in the object that comes back from JSP to Controller.
From my Controller I pass a ModelAndView with an object of class Historic.
In the JSP page I have access to all of the values of this object, but when I submit I just get part of this information, some looses on the way on.
Controller:
#GetMapping("/tt")
public ModelAndView index(Model model) {
HistoricBO historic = new HistoricBO();
// ... I fulfill this object ...
return new ModelAndView("tt", "historic", historic);
}
In JSP I have access to all the information that I passed.
I use the values in two different ways. The first one (information that later I won't be able to recover) is:
<form:form method="POST" action="/addInput" modelAttribute="historic">
....
<form:label path="userHistoric[0].user.name" />
<form:input path="userHistoric[0].user.name" disabled="true" />
Being userHistoric a list inside HistoricBO object.
And the other way that I use the object values is daoing loop to the registers and show them. I can have these values after submit:
c:forEach items="${historic.userHistoric[0].periods[0].registers}" var="reg" varStatus="rog">
...
<td class="tab-odd">
<form:input path="userHistoric[0].periods[0].registers[${rog.index}].hours[0]" class="monin" type="number" />
</td>
The method that catch the submit is as follows:
#PostMapping("/addInput")
public String savePeriod(
#ModelAttribute("historic") HistoricBO inputs,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
...
And here the object inputs only has setted the hours values, the rest of the object is empty.
Can you please why is the info loosing and how to solve it?
Thanks
Remove disabled="true" and use readonly="true" or readonly="readonly" instead like below.
<form:input path="userHistoric[0].user.name" readonly="readonly" />
Disabled values will not be submitted with the form.
See this values-of-disabled-inputs-will-not-be-submitted and demo here.

modelAttribute in mustache Templates (Spring-Boot App) / binding form data

I'm working on a Spring-Boot app which handles form data. My question is, if there is a possibility to bind the form data in case of validation errors for example.
My case:
form.mustache:
<form action="/form/basisdata" method="post" name="basisdata">
<label for="contactName">Kontakt / Ansprechpartner*:</label>
<input type="text" name="contactName"/>
<label for="emailAddress">E-Mail-Adresse*:</label>
<input type="text" name="emailAddress"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<button class="a-button" type="submit">Weiter</button>
</form
Controller method:
#PostMapping("/basisdata")
public ModelAndView setFormBasisdata(#Valid #ModelAttribute("basisdata") Basisdata basisdata, BindingResult bindingResult, Map<String, Object> model) {
if (bindingResult.hasErrors()) {
List<Error> errorList = getErrors(bindingResult);
model.put("errors" , errorList);
model.put("basisdata", basisdata);
return new ModelAndView("formBasisdata", model);
}
return new ModelAndView("formNextStep", model);
}
In case of validation errors we're returning correctly to the same form page and shows the list of errors. But the form stays empty. I would prefer it, if the form is prefilled with the values that were entered before.
Is returning ModelAndView in that case the wrong option?
In jsp templates using spring forms there is an attribute in the form, that specifies the model (modelAttribute) in thymeleaf it's th:object. Is there something that I need to change / add in my mustache template?

<option> returning emptyin UI form:select of spring mvc3

I've a list of values to be passed from my controller to the jsp page. I've the below controller:
#RequestMapping(value="/addClient.do", method = RequestMethod.GET)
protected ModelAndView Submit(HttpServletRequest request, HttpServletResponse response) throws Exception {
MyForm = new MyForm();
MyForm.setClientList(MyService.getClientList(/*"30-JUN-15"*/));
System.out.println("Size of list : "+MyForm.getClientList().size()); //-- Displayed as 10 which is correct
ModelAndView model = new ModelAndView("feeMaintenance");
model.addObject("clientForm",MyForm);
model.addObject("selectedMenu", "MenuSelected");
model.addObject("clientsList",MyForm.getClientList());
return model;
}
And my jsp form is as below:
<body>
<form:form method="post" modelAttribute="clientForm" action="${userActionUrl}">
<tr> <td align="left">
<form:select path="clientList">
<form:option value="-" label="------Select Client ------">
<form:options items="${clientsLists}">
</form:options></form:option></form:select>
</tr> </td>
</form>
</body>
I've removed the additional unrelated code. The drop down only shows ----Select Client--- even though the controller shows the correct values of the clientList. Unable to figure out whats missing.
if MyForm.getClientList() is successfully return list of client data than
rewrite this line into jsp page.
you write key name into controller is clientsList and you write this into jsp page is clientsLists this is wrong.
I hope this is work.
try this code.
model.addObject("country", projectservice.getallCountry());
**Note:**itemLabel name is same as property name into pojo class and also itemValue name.

Simple JSP-Spring 3 dropdown list not working

I know this should be pretty easy but I'm stuck after trying several things.
I'm only trying to display in my jsp a basic dropdown list. Spring version is 3 so I want everything to work with annotations.
JSP form with dropdown list:
<form:form method="post" commandName="countryForm">
<table>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="Select" label="Select" />
</form:select>
</td>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
CountryForm.java is a plain object with a single String attribute "country", with its getters and setters.
Controller who deals with the GET request is the following:
#Controller
public class CountryFormController {
#RequestMapping(value = "MainView", method = RequestMethod.GET)
public String showForm(Map model) {
CountryForm cform = new CountryForm();
model.put("countryForm", cform);
return "MainView";
}
}
However, when I redirect to the JSP "MainView" I get the typical error:
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'countryForm' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:424)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
What am I doing wrong?
The select tag in the Spring TagLib needs to be provided with a collection, map or array of options. I'm not sure what you would like these to be so I will make some assumptions.
You need to include a collection, map or array of objects in your controller. Ideally you would have a Country class and create new instances for a set of countries. For the example to work with your code, I just created a static list of countries. Add the list to your model and then modify the select tag, setting the options to ${countries}. Assuming country is a field of type String on CountryForm with appropriate get/set methods, the country should data-bind to field when the form is submitted.
Controller
#Controller
public class CountryFormController {
#RequestMapping(value = "MainView", method = RequestMethod.GET)
public String showForm(Map model) {
List<CountryForm> cfs = new ArrayList<CountryForm>();
cfs.add("United States");
cfs.add("Canada");
model.put("countries", cfs);
model.put("countryForm", cform);
return "MainView";
}
}
JSP
<form:select path="countryForm.country" options="${countries}"/>
I have sample code at GitHub, try it an let me know. Look at landing.jsp and UserController
<form:select path="users[${status.index}].type" >
<form:option value="NONE" label="--- Select ---"/>
<form:options itemValue="name" itemLabel="description" />
</form:select>
HTH

how to do binding in Spring annotated request parameter?

i have a controller that is using annotation for request mapping and requestParam.
the controller is working fine. However when submitting a command object with array, spring will crap out saying array index out of bound. i am guessing there is something wrong with binding but don't know how to fix it.
to be more specific, in eclipse i would set debugger at the beginning of the controller, and when submitting the form (by hitting a input submit button) eclipse debugger will not trigger and i will see array index out of bound error in console.
the controller is something like this:
#RequestMapping(value = {"/internal/pcsearch.dex", "/external/pcsearch.dex"},
method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView executeProductCatalogSearch(
HttpServletRequest request,
#RequestParam(value = "cat" ,required = false) String cat,
#RequestParam(value = "brand" ,required = false) String brand,
#ModelAttribute("command") ProductCatalogCommand cmd
){
[edit]
and the jsp is like:
<form name="pForm"
id="pForm"
action="<c:url value="psearch.dex"><c:param name="cat" value="${cat}"/></c:url>"
method="POST"
style="display:inline;">
...
...
<c:forEach var="model" items="${models}" varStatus="modelLinkStatus">
<script>
var modelImg<c:out value="${modelLinkStatus.index}"/>Src = '<c:out value="${model.altModelImage}"/>';
</script>
<spring:bind path="command.models[${modelLinkStatus.index}].modelSkusDisplayed">
<input type="hidden" name="<c:out value="${status.expression}"/>" id="<c:out value="${status.expression}"/>" value="<c:out value="${status.value}"/>"/>
</spring:bind>
<spring:bind path="command.updateCartButton">
<input type="submit" value="<spring:message code="orderEntryMessages.ecatalog.button.addToCart" text="Add to Cart" htmlEscape="yes" />" name="<c:out value="${status.expression}"/>" id="<c:out value="${status.expression}"/>" class="sub_buttons"/>
</spring:bind>
...
and the command object declare the model array as:
private List<ModelLink> models = new ArrayList<ModelLink>();
where modelLink is a custom ds.
the first foreach tag handle the the model command object and the 2nd part is the submit button i clicked on.
i think you should use AutoPopulatingList as models to bind list to view and controller. for example please refer link. This might resolve your problem of index.

Resources