How to modify a record displaying a form in a view - spring

I am trying to accomplish the following:
I have a list of fruits, that are stored in a table with two columns "id", "name" and "color".
Next to each fruit, I got a "modify" button. What I want to do here is being able to display the fruit in a form and being able to modify the "name" and "color" attributes.
I don't understand why, but when I click the "modify" button, the form is being displayed but the properties of the fruits that I clicked are not.
Here is the code:
Controller:
#RequestMapping(value = "/fruit/modify", method = RequestMethod.POST)
public String modifyFruit( #RequestParam("id") int id, ModelMap model) {
Fruit fruit = fruitManager.getFruitById(id);
model.addAttribute("fruit", fruit);
return "redirect:/modifyfruit";
}
#RequestMapping(value = "/modifyfruit", method = RequestMethod.GET)
public String showAddForm(#ModelAttribute("fruit") Fruit fruit, ModelMap model) {
model.addAttribute("fruit", fruit);
return "/secure/modifyfruit";
}
Here is the modify button that I am displaying next to each fruit in my list:
<td>
<c:url var="modifyUrl" value="/fruit/modify.html"/>
<form id="${fruitForm}" action="${modifyUrl}" method="POST">
<input id="id" name="id" type="hidden" value="${fruit.id}"/>
<input type="submit" value="modify"/>
</form>
</td>
Here is the modifyfruit.jsp that I am using to display the form that I want to populate:
<body>
<form:form method="post" commandName="fruit">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0"
cellpadding="5">
<tr>
<td align="right">Name:</td>
<td><form:input path="title" value="${fruit.name}"/></td>
</tr>
<tr>
<td align="right">Color:</td>
<td><form:input path="color" value="${fruit.color}"/></td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Post Ad">
</form:form>
</body>

Your redirect is simply going to that new URL without any request params being added. Therefore your fruit ID is being discarded, which is why nothing gets displayed.
The redirect seems pointless - why not return the same view name string as the GET version instead?
To redirect with the params, try:
return "redirect:/modifyfruit?id=" + id;
EDIT: just noticed you have added the Fruit to the model - this does not get transferred in a redirect and wouldn't work anyway.

Related

Grails Ajax table - how to implement?

I've input:
<g:form role="search" class="navbar-form-custom" method="post"
controller="simple" action="addEntry">
<div class="form-group">
<input type="text" placeholder="Put your data HERE"
class="form-control" name="InputData" id="top-search">
</div>
</g:form>
And table:
<table class="table table-striped table-bordered table-hover " id="editable">
<thead>
<tr>
<th>Name</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<g:render template="/shared/entry" var="entry"
collection="${entries}" />
</tbody>
</table>
Controller:
#Secured(['ROLE_USER', 'ROLE_ADMIN'])
class SimpleController {
def springSecurityService
def user
def index() {
user = springSecurityService.principal.username
def entries = Entry.findAllByCreatedBy(user)
[entries: entries]
}
def addEntry(){
def entries = Entry.findAllByCreatedBy(user)
render(entries: entries)
}
}
I just want to dynamically update the table with data from input string.
What is the best way?
Will be grateful for examples/solutions
You can update the table using AJAX with Grail's formRemote tag.
Input form
<g:formRemote
name="entryForm"
url="[controller: 'entry', action: 'add']"
update="entry">
<input type="text" name="name" placeholder="Your name" />
<input type="submit" value="Add" />
</g:formRemote>
HTML table
<table>
<thead>
<tr>
<th>Name</th>
<th>Created</th>
</tr>
</thead>
<tbody id="entry">
<g:render
template="/entry/entry"
var="entry"
collection="${entries}" />
</tbody>
</table>
Entry template
<tr>
<td>${entry.name}</td>
<td>${entry.dateCreated}</td>
</tr>
Controller
import org.springframework.transaction.annotation.Transactional
class EntryController {
def index() {
[entries: Entry.list(readOnly: true)]
}
#Transactional
def add(String name) {
def entry = new Entry(name: name).save()
render(template: '/entry/entry', collection: Entry.list(), var: 'entry')
}
}
How it works
When the add button is pressed the add controller method is called. The controller method creates the domain instance and renders the _entry.gsp template. But instead of refreshing the browser page, the template is rendered to an AJAX response. On the client side, the rendered template is inserted into the DOM inside of the tbody element with id entry, as defined in the formRemote tag by the update attribute.
Note that with this approach all of the entries are re-rendered, not just the new one. Rendering only the new one is a bit trickier.
Resources
Complete source code for my answer
Grails AJAX
Just to give you direction ( you are not showing any of your controller and js code.):
Create an action your controller ( the responsible controller) that will render the template /shared/entry by passing entries collection.
On submit of the form make ajax call to the action defined above, then replace the tbody html by the returned view fragment(template).

ModelAttribute returns null values in controller in Spring MVC

Ok, its time to seek help; I am sending a (shopping) Cart ModelAttribute to my jsp, allowing the user to edit the quantity, when the Model is POST to the controller the fields are null except the editable (quantity) field. I have researched for days on similar issues but nothing is matching. I am using spring 3.1.
Here is my controller on the GET and POST:
#Controller
public class CartController {
#Autowired
private Cart cart;
#RequestMapping(value = "/cart", method = RequestMethod.GET)
public String showCart(Model model) {
logger.debug("CartController.showCart() Cart: {}", this.cart);
model.addAttribute(cart);
return "cart/cart";
}
and POST
#RequestMapping(value = "/cart", method = RequestMethod.POST, params = "update")
public String update(#ModelAttribute("cart") Cart cart, BindingResult result, Model model) {
logger.debug("CartController.update() Cart: {}", cart);
return "cart/cart";
}
my jsp:
<div class="container MainContent">
<form:form method="POST" modelAttribute="cart">
<fieldset>
<legend>Cart</legend>
<table class="table">
<thead>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
<c:forEach items="${cart.cartDetails}" var="cartDetail" varStatus="status">
<tr>
<td>${cartDetail.product.name}</td>
<td><form:input path="cartDetails[${status.index}].quantity" size="1" /></td>
<td>${cartDetail.price}</td>
</c:forEach>
<tr>
<b><td colspan="2" align="right"><spring:message code="order.total" /></b>
</td>
<td>${cart.totalCartPrice}</td>
</tr>
</tbody>
</table>
</fieldset>
<div></div>
<button id="order" name="order">
<spring:message code="button.order" />
</button>
<button id="update" name="update">
<spring:message code="button.update" />
</button>
</form:form>
</div>
and the log results for cart before on GET:
CartController.showCart() Cart: Cart [cartDetails=[CartDetail
product=com.Product#c26440[name=My Name],
quantity=1]], totalCartPrice=10.00]
and after updating the quantity from 1 to 3 in the jsp and then POST to the controller:
CartController.update() Cart: Cart [cartDetails=[CartDetail
[product=null, quantity=3]], totalCartPrice=null]
I've read several similar post here and on the Spring forum and tried different suggested solutions with no luck. It seems like my edited quantity results are getting bound to the Object correctly but why aren’t the others?
Assuming you have all the necessary fields in your Form object;
You have to specify the form fields and fill the value with your data.
<td>${cartDetail.product.name}</td>
will only print the result to the screen. If you want to bind it to your form you have to put it in a spring form input such as:
<form:input path="productName" value="${cartDetail.product.name}"/>
If you don't want it to be editable then you can put it into a hidden field but in the end you'll have to put it in a form element in the jsp and have a corresponding field in your form POJO
Seems other fields aren't bound, try to bind for example product name
<td>${cartDetail.product.name}
<form:hidden path="cartDetails[${status.index}].product.name" value="${cartDetail.product.name}"/></td>
I once spent a lot of time investigating a similar issue. Finally I found the culprit inside a Binder's initialization method:
#InitBinder
void initBinder(final WebDataBinder binder) {
binder.setAllowedFields("name", ...);
}
This method sets a restriction on fields that are allowed for binding. And all the other fields are unbound, naturally resulting in null values.
The other possible reason: incorrect setters in a Bean annotated with #ModelAttribute. For example, Object setName(String name) instead of void setName(String).

How to send back the model data from jsp to controller

I have a controller which sets few values to a model and sends to jsp. In jsp i need to show those values(as labels) along with additional values from user as input values. When i submit the jsp i only get valid values that user has entered and the values set earlier by controller is null.
JSP
<form:form
action="${pageContext.request.contextPath}/admin/deviceAction.html"
modelAttribute="deviceData">
<table class="gridtable" width="500px">
<tr>
<td>Device Name : </td>
<td>${deviceData.deviceName}</td>
</tr>
<tr>
<td>Model Name : </td>
<td>${deviceData.modelName}</td>
</tr>
<tr>
<td>Serial No : </td>
<td>${deviceData.serialNo}</td>
</tr>
<tr>
<td>Device Id : </td>
<td>${deviceData.deviceId}</td>
</tr>
<tr>
<td>Status : </td>
<td>${deviceData.statusCode}</td>
</tr>
<tr>
<td>Action : <span class="required">*</span></td>
<td>
<form:select path="deviceAction" >
<form:option value="" label="--- Select ---" />
<form:options items="${model.actionList}" />
</form:select>
</td>
</tr>
</table>
<input type="submit" value="Submit" id="btn_submit">
</form:form>
Controller:
public ModelAndView beforeSubmit() {
ModelAndView modelView = new ModelAndView();
DeviceData deviceData = new DeviceData();
deviceData.setDevicePk("123");
deviceData.setAccessToken("abcwetrwertewrtetr");
deviceData.setDeviceId("deferterterterterwtetetertg");
deviceData.setDeviceName("test");
deviceData.setEnrolledDate("7-8-13");
deviceData.setModelName("test1");
deviceData.setSerialNo("test2dsfgdfgdfg");
deviceData.setStatusCode("test3");
List<String> actionList = getActionList();
Map<String, List<String>> model = new HashMap<String, List<String>>();
model.put("actionList", actionList);
modelView.addObject("deviceData", deviceData);
modelView.addObject("model", model);
modelView.setViewName("admin/tokenSearchResult");
}
public ModelAndView afterSubmit() {
#ModelAttribute("deviceData") DeviceData deviceData, BindingResult result) {
logger.info("#################device datas are : " + deviceData.getDevicePk() + "###### " + deviceData.getDeviceAction());
return new ModelAndView();
}
deviceData.getDevicePk() is null
Only the drop down value is having valid value. Other values displayed in the screen are received as null.
Edit:
Till now i have found only one solution:
<form:input path="deviceName" readonly="true" />
But this way UI does not looks good. The editable and non editable values mixup in the screen. Looking for a better answer
Finally i am using hidden parameters to solve the problem.
Example:
<td>${deviceData.deviceName}</td>
is replaced by:
<td><form:hidden path="deviceName"</td>
By this way it helps me to avoid any css work(which i am not much comfortable)
If anyone get a better solution kindly post it here
You need to make them into form inputs using the Spring form tags in much the same way as you have for the form:select. If they are not editable by the user, you can always disable them.
You can simple hide those input. For example :
<input type="hidden" name="VehSeriesModelId" value="${vehDetailsVM.id }">
This way, you can get the data to the controller and the user will also not be able to edit the value. On the other hand, your form will also not show it :)

Spring MVC: list of checkboxes not returned to controller on POST

Why doesn't the server see my list of filled checkboxes?
This question seems to be here asked many times, but the details are so different for each requester that it seems a different answer is needed each time. Here is my story.
These are my data-bearing classes. The Offer contains a list of Filter objects in the filter attribute:.
public class Offer implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private Long id = null;
#Column(name="title")
private String title = null;
[snip]
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name = "offer_filter",
joinColumns = { #JoinColumn(name = "offer_id", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "filter_id", nullable = false, updatable = false) })
private List<Filter> filters;
[snip]
}
public class Filter implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private Long id;
#NotBlank
#Length(max=100)
#Column(name="text")
private String text;
[snip]
#Transient
private boolean owned = false;
[snip]
}
The simple controller sends the offerEdit.jsp page, with a fully-populated Offer object. The object contains a list of Filters. Because of the owned attribute, only one of the three Filters is pre-checked. This simulates my eventual plan, where the list of Filters is the whole universe and what the Offer owns is a subset.
Note the annotations, that the Offer has the filter list going to the web page but doesn't see it coming back.
public class OfferController {
[snip]
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(#RequestParam("id") Long id, Model model, HttpSession session) {
Offer offerAttribute = offerService.get(id);
// At this point, offerAttribute.filters has three elements.
// Mockup -- tells web page that only the middle one of the three Filters should be checked.
List<Filter> filters = offer.getFilters();
Filter filter = filters.get(1);
filter.setOwned(true);
model.addAttribute("offerAttribute", offerAttribute);
return "offer/offerEdit";
}
#RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(#RequestParam("id") Long id, #Valid #ModelAttribute("offerAttribute") Offer offerAttribute, BindingResult result, HttpSession session, Model model) {
// At this point, offerAttribute.filters is null.
if(result.hasErrors()) {
result.reject("offer.invalidFields");
return "offer/offerEdit";
}
offerAttribute.setId(id);
offerService.edit(offerAttribute);
return "redirect:/offer/list";
}
[snip]
}
The web page has this for its checkbox section. I use form:checkbox over form:checkboxes because I want to use a table,
[snip]
<form:form modelAttribute="offerAttribute" method="POST" action="${saveUrl}">
<table>
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td><form:label path="title">Title:</form:label></td>
<td><form:input path="title" size="80" /></td>
<td><form:errors path="title" cssClass="error" /></td>
</tr>
[snip]
</table>
<table>
</table>
<table>
<c:forEach items="${offerAttribute.filters}" var="filter">
<tr>
<td><form:checkbox
path="filters"
label="${filter.text}"
value="${filter.id}"
checked="${filter.owned ? 'true' : ''}" />
</td>
</tr>
</c:forEach>
</table>
[snip]
The displayed web page has three filter checkboxes displayed, with just the middle checkbox filled in.
For the returned list, I expect the server to get only the middle checkbox, which is just what I want.
Here is what the generated checkboxes look like as source:
<table style="border: 1px solid; width: 100%; text-align:left;">
<tr>
<td>
<input id="filters1" name="filters" type="checkbox" value="1"/>
<label for="filters1">Adults (18+) desired, please</label>
<input type="hidden" name="_filters" value="on"/>
</td>
</tr>
<tr>
<td>
<input id="filters2" name="filters" checked="true" type="checkbox" value="2"/>
<label for="filters2">Quiet audiences, please</label>
<input type="hidden" name="_filters" value="on"/>
</td>
</tr>
<tr>
<td>
<input id="filters3" name="filters" type="checkbox" value="4"/>
<label for="filters3">Filter Text First</label>
<input type="hidden" name="_filters" value="on"/>
</td>
</tr>
</table>
My checkbox is set, and in the HTML. To restate my question,
Why doesn't the checkbox value get seen in the controller's POST handler?
Thanks for any answers,
Jerome.
The values of checkboxes could not be directly bind to List.
To get this working you need to create a simple pojo databean that will hold the values of your form fields in jsp. And in that databean to bind the values you need to declare int[] filterId and the values of your checkboxes will bind in that array.
Hope this helps you.
After a lot of web research and different debugging sessions, I came up with a configuration I can live with.
In my controller I provide a model attribute of "filterList", containing List. The "offerAttribute" is an Offer object, containing List filters.
The view has this sequence:
<table>
<c:forEach items="${filterList}" var="filter" varStatus="status">
<tr>
<td><input type="checkbox" name="filters[${status.index}].id"
value="${filter.id}"
${filter.owned ? 'checked' : ''} /> ${filter.text}
</td>
</tr>
</c:forEach>
</table>
When the POST is done the ownerAttribute.filters list is just as long as the original filterList object that created the checkboxes. The checked ones contains a Filter.id value. The unchecked ones contain a null. (That is, the returned filters list is "sparse".) If the user clicks on just a few checkboxes then I must parse the returned list to find those that were chosen.
Once I know the ID values of the checked-on filters, I fetch each of them through Hibernate, put them into my reconstructed Offer object and then persist them to the database.
I realize that I'm not (currently) using the form:checkbox. But it works, and I'm pressed for time here. I'll come back later, perhaps, and see what form:checkbox can do for me.

Passing object from JSP to spring controller

I have the below table in a .JSP page:
<form:form method="post" action="update.dtt" id="contactForms" modelAttribute="contactForms" >
<c:forEach items="${pList}" var="cf">
<tr>
<td align="center"><c:out value="${cf.fname}" /></td>
<td align="center"><c:out value="${cf.lname}" /></td>
<td align="center"><c:out value="${cf.cprovider}" /></td>
<td align="center"><c:out value="${cf.id}" /></td>
<td align="center"><c:out value="${cf.phone}" /></td>
<td><input type="submit" value="Update Contact"/></td>
</tr>
</c:forEach>
</form:form>
I'm iterating over the list (this is list of objects) and adding an Update Contact button for each record in the list. How can I pass on the particular instance (object) to the controller when the Update button is clicked?
The controller I have is as below. However I'm getting null.
#RequestMapping(value = "/user/update.dtt", method = RequestMethod.POST)
public String updateView(#ModelAttribute("contactForms") Banks bank, HttpServletRequest request, HttpServletResponse response, Model model) {
System.out.println("*First Name*" + bank.getFname());
//......
return "detailBank"; //name of jsp file
}
You'll need to have a hidden form field for each information you want to send to the server.
Since you have one button for each row, you should also have one form for each row. So the <form:form> and </form:form> lines should be inside the <c:forEach>, and not outside.
You need reference the instance by position, accessing to the element of the list by position.
list[i].name
list[i].surname
where list is the element in your pojo.

Resources