html thymeleaf directly post in a select option - java

I want directly push the selected option. But i dont find a solution. Maybe u can help me?
I have a table with a list of entities. And i will offer a select for every entity. But i want to save the selection directly.
I need the entry.id and the cat.id.
This is what i have.
<form class="myForms" id="uploadCheckerForm" method="post" th:action="#{uploadStatus}">
<table>
<tr th:replace="fragment/form-fragments::checkerMainLine()"></tr>
<tr th:each="entry : ${uploadList}">
<td><select th:id="transactionCategory" th:name="transactionCategory">
<option>Select</option>
<option th:each="cat : ${transactionCategoryList}"
th:text="${cat.name}" th:value="${cat.id}">
</option></select>
</td>
<td th:text="${entry.Comment}">
</tr>
</table>
</form>
What have i to do, that it directly post this infos?
Thanks for help!

I would append some unique identifier of your entry to the name of your <select> with some sort of separator and then accept form data on backend to a Map. Kinda like this:
HTML
<form class="myForms" id="uploadCheckerForm" method="post" th:action="#{uploadStatus}">
<table>
<tr th:replace="fragment/form-fragments::checkerMainLine()"></tr>
<tr th:each="entry : ${uploadList}">
<td><select id="transactionCategory" th:name="'transactionCategory_' + ${entry.guid}">
<option>Select</option>
<option th:each="cat : ${transactionCategoryList}"
th:text="${cat.name}" th:value="${cat.id}">
</option></select>
</td>
<td th:text="${entry.Comment}">
</tr>
</table>
</form>
Controller
#PostMapping( "/uploadStatus" )
public String uploadStatus( #RequestParam Map<String, Long> params ) {
for ( Map.Entry<String, Long> entry : params.entrySet() ) {
if ( entry.getKey().startsWith( "transactionCategory_" ) ) continue; // skip
Long entryId = Long.parseLong( entry.getKey().replace( "transactionCategory_", "" ) ); // get entry ID
SomeDAO.instance().uploadStatus( entryId, entry.getValue() ); // do what you need to do with id of entry and chosen category ID
}
return "redirect:/";
}

Related

How to return a single data from a row from a table in html?

I have a table that stores the product in the cart of a user. Each row has a button that enables the user to remove a single product from the cart of a user. Here is the code snippet of my html.
<form action="${pageContext.request.contextPath}/customer/removeProduct" method="post">
<input type="hidden" name="page" value="${page}">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<c:forEach items="${productsInCart}" var="product"
varStatus="status">
<input type="hidden" class="form-control" name="upc"
value="${product.getUpc()}">
<tr class="warning">
<td>${product.getName()}</td>
<td>${product.getQuantity()}</td>
<td style="color: green;">₱ ${product.getTotal()}</td>
<td><input type="submit" class="btn btn-warning btn-xs"
value="Remove from cart"></td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Here is the output.
Product in cart table
The value I want to get is the UPC of a product which is stored in a hidden input type field. However, when the 'remove from cart' button is clicked, it returns all the UPC of the product that is in the cart. Here is the code snippet of the controller.
#RequestMapping(value="/customer/removeProduct", method=RequestMethod.POST)
public String removeProduct(#RequestParam(value = "upc") String upc, HttpServletRequest request){
System.out.println(upc);
// customerService.removeProductInCart(customer.getCustomer(request).getCartId(), upc);
return "customer_home";
}
You may want to create form on every iteration to get the specific upc on each row instead of wrapping your whole table.

Spring mvc controller pass list of values to view

I have a page will show a table of data(from database) on start and I am creating multiple fields for searching/filtering purpose.
My controller:
#RequestMapping(value = "/country", method = RequestMethod.GET)
public ModelAndView getCountryList(Model model) {
List<Country> countryList = countryService.getCountryList();
model.addAttribute("dateTime", todayDate());
model.addAttribute("pageTitle", "<a href=\"/pgwrefund\" />COUNTRY</a>");
return new ModelAndView("country", "countryList", countryList);
}
#RequestMapping(value="/filterCountry")
public ModelAndView getFilteredCountryList(#RequestParam String countrycode,#RequestParam String countryname,Model model){
List<Country> filteredCountryList = countryService.getFilteredCountryList(countrycode, countryname);
model.addAttribute("dateTime", todayDate());
model.addAttribute("pageTitle", "<a href=\"/pgwrefund\" />COUNTRY</a>");
System.out.println("List country:"+filteredCountryList.size() +"\nValue:"+ filteredCountryList);
return new ModelAndView("countrytemplate","filteredCountryList",filteredCountryList);
}
My View
<tbody>
<c:forEach var="country" items="${countryList}" varStatus="loopStatus">
<tr class="tbodydata ${loopStatus.index % 2 == 0 ? 'even' : 'odd'}">
<td>${country.countryCode}</td>
<td>${country.countryName}</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</c:forEach>
</tbody>
My filtered table view:
<c:forEach var="country" items="${filteredCountryList}" varStatus="loopStatus">
<tr class="tbodydata ${loopStatus.index % 2 == 0 ? 'even' : 'odd'}">
<td class="firsttd">${country.countryCode}</td>
<td class="secondtd">${country.countryName}</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</c:forEach>
So now, What I have done here is, first the i enter values to all the field and filter. The view pass the values to controller and it will filter using a query and return back to the view BUT with another table(foreach). Basically, I am replacing the filtered data with the original data. Then problems came up, most of the functions wont work including update and delete. My goal is, my country page able to filter the table data and stay at the same page. Any help will be appreciated.

How to generate table dynamically from the Map of String and List<String> using JSP and Servlet?

I have my response Object as which contains getter and setters for the Map -
public class DataResponse {
private Map<String, List<String>> attributes = new LinkedHashMap<String, List<String>>();
public Map<String, List<String>> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, List<String>> attributes) {
this.attributes = attributes;
}
}
In the above object, I have a Map of String and List<String>. In the map, keys are my table header and the value in the map is the table data for that header.
Suppose if this is the value in the map -
FirstName is the Key in the same Map
DAVID, RON, HELLO are the values in the map as the List for that key.
Similarly,
LastName is the Key in the same Map
JOHN, PETER, TOM are the values in the map as the List for the `LastName` key.
Then my Table should look like this
FirstName LastName
David JOHN
RON PETER
HELLO TOM
I need to generate my above table dynamically as am passing my dataResponse object to my JSP page as mentioned below -
DataResponse dataResponse = some_code_here;
req.setAttribute("data", dataResponse);
WebUtil.forward(req, resp, this, "/admin/test.jsp");
And below is my table in JSP in which I am using my above object to generate the table in the above format
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
<TR>
<c:forEach var="h" items="${data.attributes}">
<TH>${h.key}</TH>
</c:forEach>
</TR>
//iterate again
<c:forEach var="h" items="${data.attributes}">
//h.value is ArrayList so we can iterate with c:forEach
<c:forEach var="headers" items="${h.value}">
<TR>
<TD>${headers}</TD>
</TR>
</c:forEach>
</c:forEach>
</TABLE>
But somehow my tables are not getting shown in the way I am trying to show in my above example. All the keys are getting shown properly in the Table Headers but all the values are getting shown only in first column.
And size of the list will be same for all the keys.
Any thought how this can be done?
UPDATE:-
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
<TR>
<c:forEach var="h" items="${data.attributes}">
<TH>${h.key}</TH>
</c:forEach>
</TR>
//iterate again
<c:forEach var="h" items="${data.attributes}">
<TR>
<c:forEach var="headers" items="${h.value}">
<TD>${headers}</TD>
</c:forEach>
</TR>
</c:forEach>
</TABLE>
This gives me -
FirstName LastName
David RON HELLO
JOHN PETER TOM
<%
// Create an ArrayList with test data
ArrayList list = new ArrayList();
Map person1 = new HashMap();
person1.put("name", "A");
person1.put("lastname", "A1";
list.add(person1);
Map person2 = new HashMap();
person2.put("name", "B");
person2.put("lastname", "B1");
list.add(person2);
Map person3 = new HashMap();
person3.put("name", "C");
person3.put("lastname", "");
list.add(person3);
pageContext.setAttribute("persons", list);
%>
<html>
<head>
<title>Search result: persons</title>
</head>
<body bgcolor="white">
Here are all persons matching your search critera:
<table>
<TH>Name</th>
<TH>Id</th>
<c:forEach items="${persons}" var="current">
<tr>
<td><c:out value="${current.name}" /><td>
<td><c:out value="${current.lastname}" /><td>
</tr>
</c:forEach>
</table>
This approach is easier and suggested.
If u still want to stick with your code, you can use jsp tags instead of jstl tags to achieve your goal as follow
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
<TR>
<c:forEach var="h" items="${data.attributes}">
<TH>${h.key}</TH>
</c:forEach>
</TR>
//use jsp scriplets to acces both list simultaneoulsy
<% List data= request.getAttribute("data")==null?null:(List) request.getAttribute("data");
List Names=data.get(0);
List LastNames=data.get(1);
for(int i=0;i<Names.length();i++){ %>
<td><%=Names.get(i)%></td><td><%=LastNames.get(i)%></td>
<%
}
%>

get map from jsp-form spring

I am new in Spring MVC, and I have a problem.
I'm sending to FORM LinkedHashMap, and it's showing great.
model.addAttribute("resultForm", resultForm);
Part of my jsp:
<c:forEach items="${resultForm}" var="resultMap" varStatus="status">
<tr id="tableRow" class="table-row">
<td>
${resultMap.key}
</td>
<td>
<select name="resultMap['${resultMap.key}']" class="espa-config-select">
<option selected value ="${resultMap.value}">${resultMap.value}</option>
<c:forEach items="${mainParams}" var="item2">
<c:if test="${item2.key == resultMap.key}">
<c:forEach items="${item2.value}" var = "q">
<c:if test="${resultMap.value != q}">
<option value="${q}"> ${q} </option>
</c:if>
</c:forEach>
</c:if>
</c:forEach>
</select>
</td>
</tr>
</c:forEach>
Now I need to get it back
Here is part of Controller
#RequestMapping( value = "espa/update", method = RequestMethod.POST )
public String save(#ModelAttribute("resultForm") LinkedHashMap<String,String> resultForm) {
System.out.println("resultMap post "+resultForm.toString());
if (resultForm!=null){
//resultForm.put("Port", port);
espaService.setConfiguration(selectedDevice, resultForm);
LOG.debug("Saving configuration: {} /nPort{}",resultForm, selectedDevice);
}
return "redirect:/espa";
}
But it is empty!
How can I fix it?
In your select you are using the name "resultMap". The name attribute needs to correlate to the Model Attribute, which you are called "resultForm".

Working with <div> tag in JSP for making the contents hidden or visible

I have written a javascript function.
function wellChecked(state) {
if (state)
{
wellDropDown.style.visibility = 'visible';
}
else
{
wellDropDown.style.visibility = 'hidden';
}
}
I have a checkbox after the Well Modification <td> as given below,
<tr>
<td>On Call</td>
<td><html:checkbox property="onCall"/></td>
<td>Well Modification</td>
<td><input type="checkbox" onclick="wellChecked(this.checked)" /></td>
</tr>
When that checkbox is clicked I want the drop down list given under the div id=wellDropDown to be displayed. Defaultly, if the check box is not clicked, the drop down should not be displayed.
<tr>
<td>Active</td>
<td><html:checkbox property="active"/></td>
<div id="wellDropDown" style="visibility:hidden;">
<td>
<html:select property="wellFormatId">
<html:option value="">(Select)</html:option>
<bean:define id="wellFormatColl" name="wellFormats" scope="request"/>
<logic:iterate id="wellFormats" name="wellFormatColl" indexId="index" type="com.astrazeneca.compis.data.WellFormatVO">
<% Long wellId = wellFormats.getWellFormatId();%>
<% String wellIdNo = wellId.toString(); %>
<html:option value="<%=wellIdNo%>">
<bean:write name="wellFormats" property="wellFormatName"/>
</html:option>
</logic:iterate>
</html:select>
</td>
</div>
</tr>
When I tried executing this code, I could see the drop down list getting displayed irrespective of the checkbox checked or not.
Where I have went wrong in this scenario? Please give ur suggestions or ways to implement my requirement.
Your HTML is invalid. You may not have a div enclose a td like this. Either make the td itself visible or invisible, or put the div inside the td, instead of putting it around the td.
Also, unless wellDropDown is a global JS variable, the code should be
document.getElementById("wellDropDown").style.visibility = 'visible';
with jquery you could do this :
<tr>
<td>On Call</td>
<td><html:checkbox property="onCall"/></td>
<td>Well Modification</td>
<td><input type="checkbox" id="myCheckBox" /></td>
</tr>
...
<script>
$('#myDropDown').click(
function () {
$("#wellDropDown").toggle();
});
);
</script>

Categories

Resources