I am developing a small application using spring mvc where I need to have option to delete each item from cart (in case customer feels he donot need after adding to cart).
I have got a "delete" button below each item item.(The items added are in a list).My pupose is when I click delete button against a particular item only that item should be removed from the cart.
I have written some code but it is remove lastest added items from cart and not required one.
I know my mistake but not able to proceed further.Here is what I implemented.
This is jsp :
<c:forEach items="${cart}" var="nextMovie">
<li>
<h2>${nextMovie.title}</h2>
</li>
<h2>Price</h2>
<h2>${nextMovie.price}</h2>
<c:set var="totalPrice" value="${0}" />
<c:forEach var="nextMovie" items="${cart}">
<c:set var="totalPrice" value="${totalPrice + nextMovie.price}"/>
</c:forEach>
<form method='post' action='<c:url value="removeFromCart.do"/>'>
<input type='image' src='Delete.png'/>
<input type='hidden' name='id' value='${nextMovie.id}'/>
</form>
</c:forEach>
This is my controller:
#RequestMapping("/removeFromCart")
public ModelAndView removeFromCart(HttpSession session) {
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
}
List<Movie> allMovies = cart.getAllItems();
for(int i= 0;i<allMovies.size();i++)
{
allMovies.remove(i);
}
return new ModelAndView("/cartContents.jsp", "cart", allMovies);
}
Please suggest me how I will be able to delete the element again the delete button from the list.
Thanks
Maruthi
[HttpPost]
[Route("~/CartDetail/DeleteCartDetail")]
public ActionResult DeleteCartDetail(CartDetailModel model)
{
var response = _cartDetailService.DeleteCartItem(model.Id);
return Json(new
{
success = response.Success,
message = response.Message
});
}
}
I am importing my data from service DeleteCartItem
Here is service code
public BaseResponse DeleteCartItem(int cartDetailId)
{
var response = new BaseResponse();
try
{
var itemCart = _context.CartDetails.FirstOrDefault(x => x.Id == cartDetailId);
if (itemCart == null)
{
response.Message = "This item does not exist in the cart.";
return response;
}
_context.CartDetails.Remove(itemCart);
_context.SaveChanges();
response.Success = true;
}
catch (Exception exception)
{
response.Message = "Some error occured : " + exception.ToString();
}
return response;
}
Your JSP has nested <c:forEach> tags, with both containing the same items expression. Either you don't need 2 of them of else you need to close the first one before starting the second.
Your application has some problems:
First, your problem is because you are using the same var attribute name, for your both foreach tags. The first tag defines an attribute named nextMovie in its scope, the second foreach which is nested within first, defines the same attribute name, and then iterates, so when its iteration completes, nextMovie will be last element in the list, so ${nextMovie.id} will be last element's id.
Second,
List<Movie> allMovies = cart.getAllItems();
for (int i= 0;i<allMovies.size();i++) {
allMovies.remove(i);
}
is equivalent of allMovies.clear(), isn't it? So you are removing all items form list, what else do you need?
Third, next problem is you have an object of type ShoppingCart in your session which is named cart, and you add an object of type List<Movie> to your model with the same name; although when EL processor tries to resolve a name request has a more priority than session, but believe me it is much better to rename one.
Forth, why are you calculating 'totalPrice' in each iteration? And what is its use?
Related
I want to change the table from the page /manager/html/sessions of Tomcat.
The jsp file for that page is tomcatpath/webapps/manager/WEB-INF/jsp/sessionsList.jsp
I want to add a new column in table which contains the path of last page which client has requested.
Ex: if the last request of client is mydom.com/path/3, I want to show in table /path/3
This is the part where are iterated all sessions
<%
for (Session currentSession : activeSessions) {
String currentSessionId = JspHelper.escapeXml(currentSession.getId());
String type;
if (currentSession instanceof DeltaSession) {
if (((DeltaSession) currentSession).isPrimarySession()) {
type = "Primary";
} else {
type = "Backup";
}
} else if (currentSession instanceof DummyProxySession) {
type = "Proxy";
} else {
type = "Primary";
}
//I have problem getting the last accessed path by client.
String lastPath = ...;
%>
//html where is printed every row with data from session
//use here <%= lastPath %>
<%
} //end of for
%>
I don't know how to extract the last accessed path.
Tomcat version: Apache Tomcat/9.0.20
I created adrop down list as follows:-
Teacher Name: <select name="teacher" >
<c:forEach var="currTeacher" items="${listTeacher}">
<option value="${currTeacher.teacherId}">${currTeacher.teacherName}</option>
</c:forEach>
</select>
The snapshot for drop down list is here
I am retrieving its value as String teacherName=(String) actionRequest.getParameter("teacher");
But when I am printing value of teacherName, it is printing null. So what could be the problem?I want to tell that I submitted the form successfully and on submission I am calling the method addStudent()Inside addStudent() I am retrieving the parameter as shown above.Please help. Thanx in advance.
The code for addStudent() is as follows:-
public void addStudent(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException,SystemException {
try {
System.out.println("Student : "+StudentLocalServiceUtil.getStudentByGenderMale());
String firstName = ParamUtil.getString(actionRequest, "firstName");
String lastName = ParamUtil.getString(actionRequest, "lastName");
int studentAge = ParamUtil.getInteger(actionRequest, "studentAge");
int studentGender = ParamUtil.getInteger(actionRequest, "sex", 1);
String address = ParamUtil.getString(actionRequest, "address");
String teacherName=(String) actionRequest.getParameter("teacher");
System.out.println("teacher name " + teacherName);
// add student record
// create primary key
long studentId = CounterLocalServiceUtil.increment();
// create student persistance object
Student student = null;
student = StudentLocalServiceUtil.createStudent(studentId);
// fill the data in persistance object
student.setFirstName(firstName);
student.setLastName(lastName);
student.setStudentAge(studentAge);
student.setStudentGender(studentGender);
student.setStudentAddress(address);
// Add student persistance object to database student table
student = StudentLocalServiceUtil.addStudent(student);
if (student != null) {
// adding success message
SessionMessages.add(actionRequest.getPortletSession(),
"student-add-success");
_log.info("Student have been added successfylly");
} else {
SessionErrors.add(actionRequest.getPortletSession(),
"student-add-error");
_log.error("There is an Erron in adding Student");
}
// navigate to add student jsp page
actionResponse.setRenderParameter("mvcPath",
"/html/jsps/add_student.jsp");
} catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),
"student-add-error");
e.printStackTrace();
}
}
I had observed similar type of issue, while migrating a legacy portlet to Liferay 6.2
From Liferay 6.2, portlet action class will only consider those request
parameters which have appended portlet namespace with them. This is
default behavior of Liferay 6.2 portlet action class. more...
There are three possible solutions to this problem:
Migrate your sample HTML form fields to AUI, which automatically appends portlet namespace at its own.
Use sample HTML form fields and manually append portlet namespace to it using <portlet:namespace/> or renderResponse.getNamespace().
Use sample HTML form fields and set <requires-namespaced-parameters> to false in liferay-portlet.xml.
I got the solution..I just used alloy ui to create form and I got the parameter value which I passed during form submission.
I have the following form with repeating items:
#(adverts: List[models.AdvertModel])
#if(adverts.size() > 0 && adverts != null) {
#helper.form(action = routes.UserController.editAdvert()) {
#for( (advert, index) <- adverts zip (Stream from 0)) {
<div>#adverts.get(index).title</div>
<button type="submit" name="delete" id="delete_#index">delete</button>
}
}
and this controller:
public Result editAdvert() {
String[] indices = request().body().asFormUrlEncoded().get("delete");
if (indices != null) {
// delete advert
}
return ok();
}
I would like to be able to delete adverts according to their ids but with the current code my array contains a String "delete" instead of i.e. "delete_0".
How do I get the index of the clicked button?
I finally got it:
tldr:
add value="delete_#index" to the button.
longer answer:
The value returned by request().body().asFormUrlEncoded().get("delete")
is saved in the value attribute of the button with name="delete" in the scala template.
Therefore, by adding a value="delete_#index" to the button, we will get a String such as delete_0.
As #danielnixon commented, this is not a play-specific behaviour, but simply how html forms work.
I have a very peculiar problem. I am developing a web application in Java and Spring MVC. I have a row that can be duplicated dynamically by the user on the press of a button. Each row has around 10 fields. I am binding these rows as list of objects in the backing bean and initializing this list as a lazy list in the bean. Now, it has been working fine till now but the user tried to enter 12 rows and on the 12th row, i.e., the 11th iteration(the iteration starting from 0), the 5th field becomes empty, although the user enters values and all the other fields retain their values. Since the binding happens with name, I have checked the name of the field, it is consistent with the rest of the fields in the same row and the rest of the rows. I am unable to debug and rectify the issue. This is affecting the code in production.
I can provide whatever code snippets are required.
Can somebody please help me with this. Thanks in advance.
EDIT: I tried executing the same code on a different server and it works fine there but still persists on the live server. And the problem seems to be only in the 11th iteration's 5th field. Could it be a problem with the server
Adding code:
JSP:
<c:forEach items="${addProposal.requirements}" var="req" varStatus="status">
<!--Rest of the fields-->
<form:input path="requirements[${status.index}].sampleSize" id="r_sample${status.index}" value="${addProposal.requirements[status.index].maximumFeasibility}" class="inptform2" style="width:65px;" size="10" onchange="functions();"/>
<!--Rest of the fields-->
<td width="57" align="left" valign="middle" id="btn-close" class="btn-remove">' +
'<a href="javascript:void(0)"><img src="images/btncross.png" width="18" height="17" border="0" />' +
'</a>
</td>
</c:forEach>
Javascript:
$(document).ready(function(){
//Add more dynamic rows
$("#addMore").click(function() {
var tr_temp=$("#requirement tr:first").clone();
//rest of the fields code
tr_temp.find("#r_sample0").each(function() {
$(this).attr({
'id': function(_, id) { return 'r_sample' + i},
'name': function(_, name) { return 'requirements[' + i + '].sampleSize'},
'value': ''
});
}).end();
tr_temp.find("td:last").remove();
tr_temp.append(btn_close);
tr_temp.appendTo("#requirement");
i++;
});
//To remove a dynamically added row
$("#btn-close").live('click',function(){
doNotDel=false;
count=0;
//To fetch the values of the Input Fields
$(this).parent().find("input").each(function(){
count++;
var value = $(this).val();
var id=$(this).attr('id');
if(id.indexOf("r_total")==-1){
//Skip the minutes and currency column
if(id.indexOf("minutes")==-1 && id.indexOf("currencyValF")==-1 && id.indexOf("currencyVal")==-1){
if(value!=""){
doNotDel=true;
return false; //breaks the .each loop
}
}
}
});
if(doNotDel==false){
$(this).parent().remove();
}
});
});
Bean:
private List<RequirementBean> requirements;
//in constructor
requirements = LazyList.decorate(
new ArrayList<RequirementBean>()
, new InstantiateFactory(RequirementBean.class));
Controller:
#RequestMapping(value="/addProposal", method=RequestMethod.POST)
public String addProposal(#ModelAttribute("addProposal") ProposalBean proposal, ModelMap model){
RequirementBean req;
List<RequirementBean> reqmtList;
System.out.println("Before empty rows");
reqmtList = proposal.getRequirements();
for(int i=0; i<reqmtList.size(); i++){
req = reqmtList.get(i);
if(req.getCountry()!=null){
System.out.println("sample size " + i + " :" + req.getSampleSize());
}
}
}
EDIT:
I tried changing the value of the 4th row in the same column, and now the code seems to work. I am still not able to understand what is the issue.
Hope this gives more clarity. Please help me.
I'm currently trying to save search criteria attributes to the session between two pages: search page and edit page. The goal is to save the three variables: sYear, submission, collectionPeriod. I'm adding these to the session here below in the Search screen controller:
request.getSession().setAttribute("sYearSave", sYear);
request.getSession().setAttribute("submissionSave", submission);
request.getSession().setAttribute("collectionPeriodSave", collectionPeriod);
In the edit screen controller, I set a BooleanisFromEditScreen to true. This is so I know that I'm coming from the edit screen. I do print out the variables and I do get the values correctly here in the edit controller screen.
request.getSession().setAttribute("isFromEditScreen", new Boolean(true));
sYearSave = (String)request.getSession().getAttribute("sYearSave");
collectionPeriodSave = (String)request.getSession().getAttribute("collectionPeriodSave");
submissionSave = (String)request.getSession().getAttribute("submissionSave");
But the problem is when I use a back button to go back to the Search screen, the search criteria sYearSave, collectionPeriodSave, and submissionSave values return NULL. For some reason, the isFromEditScreen boolean works just fine and returns true. It actually enters the statement but the search criteria return null. The Search controller code is below:
if (isFromEditScreen != null && isFromEditScreen == true) {
System.out.println("Inside isFromEditScreen ==== true");
sYear = (String)request.getSession().getAttribute("sYearSave");
collectionPeriod = (String)request.getSession().getAttribute("collectionPeriodSave");
submission = (String)request.getSession().getAttribute("submissionSave");
sYearSave = (String)request.getSession().getAttribute("sYearSave");
collectionPeriodSave = (String)request.getSession().getAttribute("collectionPeriodSave");
submissionSave = (String)request.getSession().getAttribute("submissionSave");
System.out.println("sYearSave ==== " + sYearSave);
System.out.println("submissionSave ==== " + submissionSave);
System.out.println("collectionPeriodSave ==== " + collectionPeriodSave);
System.out.println("isFromEditScreen set in else ==== " + isFromEditScreen);
}
Any help would be greatly appreciated!
If you are using Spring MVC (as the question tag suggests), why not try using SessionAttributes annotaion and use the ModelAndView API from Spring? Also make sure the attribute name is unique across the application.
#RequestMapping("view-name")
#SessionAttributes( { "isFromEditScreen" })
public class YourController {
...
#RequestMapping
public ModelAndView display() {
ModelAndView modelAndView = new ModelAndView("view-name");
modelAndView.addObject("isFromEditScreen", new Boolean(true));
return modelAndView;
}
...
}
My session attributes were being overwritten. Overlooked mistake.