how to display data in edit modal with thymleaf - button

I want to populate the data in my table when an edit button is clicked, I have already displayed those data in a table with a button corresponding to each row and when I click the button,I want the edti modal popup to populate the information in that row, the popup modal is displayed when I click on it but it is blank. No data is populated in it. I don't really know how to go about it.
Here is the code
Data class
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Country {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String code;
private String capital;
private String description;
private String nationality;
private String continent;
#OneToMany(mappedBy = "country")
private List<State> states;
}
here is my controller
#Controller
public class CountryController {
#Autowired
private CountryService countryService;
#GetMapping("/countries")
public String getCountries(Model model) {
List<Country> countryList = countryService.getAllCountries();
model.addAttribute("countries",countryList);
return "country";
}
#PostMapping("/countries/addNew")
public String saveInfo(Country country){
countryService.saveCountryInfo(country);
return "redirect:/countries";
}
#GetMapping("/country/{id}")
public String findById(#PathVariable Long id, ModelMap modelMap) {
modelMap.put("id", id);
Country country = new Country();
country.setId(id);
country.setCapital(country.getCapital());
country.setCode(country.getCode());
country.setContinent(country.getContinent());
country.setDescription(country.getDescription());
country.setNationality(country.getNationality());
modelMap.put("country", country);
return "country";
}
}
Here is my html page
<section class="section dashboard">
<div class="row">
<!-- Left side columns -->
<div class="row">
<div class="col-lg-9 col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<!-- Image background -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal" data-whatever="#mdo">Add A Country</button>
<h1>List of Country</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Code</th>
<th>Capital</th>
<th>Description</th>
<th>Nationality</th>
<th>Continent</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="country:${countries}">
<td th:text="${country.getId}"></td>
<td th:text="${country.getCode}"></td>
<td th:text="${country.getCapital}"></td>
<td th:text="${country.getDescription}"></td>
<td th:text="${country.getNationality}"></td>
<td th:text="${country.getContinent}"></td>
<td>
<div class="btn-group">
<a th:href="#{/country/{id} (id=${country.getId})}" class="btn btn-primary"data-bs-toggle="modal" data-bs-target="#editModal" data-whatever="#mdo">Edit</a>
</div>
</td>
</tr>
</tbody>
</table>
</div><!-- End of Image background -->
</div><!-- End Left side columns -->
</div>
</div>
</div>
</section>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editModalLabel">Update Country</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form th:objec="${country}" th:action="#{/country/update}" method="put">
<div class="form-group">
<label for="idEdit" class="col-form-label">Id:</label>
<input type="text" class="form-control" id="idEdit" name="id" th:value="*{id}">
</div>
<div class="form-group">
<label for="codeEdit" class="col-form-label">Code:</label>
<input type="text" class="form-control" id="codeEdit" name="code" th:value="*{code}">
</div>
<div class="form-group">
<label for="capitalEdit" class="col-form-label">Capital:</label>
<input type="text" class="form-control" id="capitalEdit" name="capital" th:value="*{capital}">
</div>
<div class="form-group">
<label for="descriptionEdit" class="col-form-label">Description:</label>
<input type="text" class="form-control" id="descriptionEdit" name="description" th:value="*{description}">
</div>
<div class="form-group">
<label for="nationalityEdit" class="col-form-label">Nationality:</label>
<input type="text" class="form-control" id="nationalityEdit" name="nationality" th:value="*{nationality}">
</div>
<div class="form-group">
<label for="continentEdit" class="col-form-label">Continent:</label>
<input type="text" class="form-control" id="continentEdit" name="continent" th:value="*{continent}">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Related

ASP.Net Core MVC CRUD PopUp Modal

I am just starting to work with ASP.Net Core MVC. I have difficulty in creating a popup modal. I've tried to create a simple page. 
Below is my model:
namespace CoreModal.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
}
Below is my EmployeeController:
namespace CoreModal.Controllers
{
public class EmployeeController : Controller
{
public static List<Employee> empList = new List<Employee>() {
new Employee {Id=1, Name="John", Email="john#gmail.com", Address="Campbell", Phone="1234"}
};
public IActionResult Index()
{
ViewBag.Employee = empList;
return View();
}
[HttpPost]
[Route("create")]
public IActionResult Create(string name, string email, string address, string phone)
{
var newEmployee = new Employee
{
Name = name,
Email = email,
Address = address,
Phone = phone
};
empList.Add(newEmployee);
ViewBag.Employee = empList;
return RedirectToAction("Index");
}
}
}
In my Index View, I create a button to trigger a popup modal for creating a new Employee object as follow:
<i class="material-icons"></i><span>Add New Employee</span>
<d id="addEmployeeModal" class="modal fade" name="addEmployeeModal">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" asp-controller="employee" asp-action="create">
<div class="modal-header">
<h4 class="modal-title">Add Employee</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" required="required" name="name"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" required="required" name="email"/>
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" required="required" name="address"/>
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" required="required" name="phone"/>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" />
<input type="Submit" class="btn btn-success" value="Add" />
</div>
</form>
</div>
</div>
</d>
But instead of directing to a popup modal, it directs it to url https://localhost:44330/#addEmployeeModal.
What did I do wrong?
Thanks
First of all, you should not be keeping your data inside the controller because the controller runs anew each time it is called and your data will be lost. Use a database for best results.
Your syntax for calling the modal is slightly wrong.
Check here for the correct syntax. It's not href (that's your mistake!) You can mostly copy this code and replace the inner parts with what you have.
https://getbootstrap.com/docs/4.0/components/modal/
*Note: you must be using bootstrap for this to work
Good Luck!
Edit : You can try this: (may need some tweaking)
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Add Employee
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="post" asp-controller="employee" asp-action="create">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" required="required" name="name"/>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" required="required" name="email"/>
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" required="required" name="address"/>
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" required="required" name="phone"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary">Add Employee</button>
</div>
</form>
</div>
</div>
</div>
Additionally, It is better practice to send a model into the controller. Use a model on the top of your view, link it to your employee model, and send that into the controller instead.

Modal always getting first Id

I have a basic feedback section, where people can reply to people's feedback. When I click the Reply button, it is supposed to open modal with text to fill and have the FeedbackParentId set to the feedback that has been clicked. However, it is always set to the first feedback.
This is the loop where I simply show all the feedback on the page.
#foreach (var comment in Model.Feedback.OrderByDescending(x => x.CreatedOn))
{
<partial name="_CommentSectionPartial" model="comment" />
}
This is the comment partial itself. Why would the modal get the first ID always?
#model FeedbackViewModel
<div class="comment-list" id="#Model.Id">
<div class="single-comment justify-content-between d-flex">
<div class="user justify-content-between d-flex">
<div class="thumb">
<img src="~/images/blog/c3.jpg" alt="">
</div>
<div class="desc">
<h5>
#Model.Name
</h5>
<p class="date">#Model.CreatedOn.Value.ToLongDateString()</p>
<p class="comment">
#Model.Comment
</p>
</div>
</div>
<div class="reply-btn">
<div class="modal fade" id="replyModal" tabindex="-1" role="dialog" aria-labelledby="replyModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="replyModalLabel">Submit Feedback for #Model.Name</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="send-reply-form" asp-action="AddReply" asp-controller="Business" asp-area="Business">
<input type="hidden" name="feedbackparentId" value="#Model.Id" />
<input type="hidden" name="businessid" value="#Model.Business.Id" />
#Html.AntiForgeryToken()
<div class="form-group form-inline">
<div class="form-group col-lg-6 col-md-6 name">
<input type="text" name="authorName" class="form-control col-form-label" id="name" placeholder="Enter Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Name'">
</div>
<div class="form-group col-lg-6 col-md-6 email">
<input type="email" name="email" class="form-control" id="email" placeholder="Enter email address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'">
</div>
</div>
<div class="form-group">
<textarea class="form-control mb-10" rows="5" name="comment" placeholder="Message" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Message'"
required=""></textarea>
</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send Feedback</button>
</form>
</div>
</div>
</div>
</div>
<button id="reply-button" type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#replyModal">Reply</button>
</div>
</div>
</div>
I tried setting the value through JS like that, does not work.
$(document).ready(function () {
$("#send-reply-form").click(function () {
$("#feedbackparentId").val($(this).data('id'));
});
});
I've fixed it with that piece of code:
$(document).on("click", "#reply-button", function () {
var feedbackId = $(this).data('id');
$(".modal-body #feedbackparentId").val(feedbackId);
console.log(feedbackId);
});

Neither BindingResult nor plain target object for bean name available as request attribute when trying to load a bootstrap modal element

In my JSP im trying to load a bootstrap modal in order to save and edit entities with relevant spring controller methods and model attributes. But when I add this modal i'm getting the following errors. When the tabs are changed, following request is passed to the spring controller which then pass a modal attribute to the view and if thats true the relevant modal shown.
http://localhost:8080/admin/setting/systemRole/load
The error on tomcat log :
DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/settings.jsp at line 181
178: <form:form method="post" modelAttribute="user" action="save">
179: <div class="form-group">
180: <label class="col-form-label">User Name</label>
181: <form:input type="text" required="required" class="form-control" path="username"/>
182: <h6 class="fieldError"><form:errors path="username"/></h6>
183: </div>
184: <div class="form-group">
But it works fine for the following request when i change the tab to the users.
http://localhost:8080/admin/setting/systemUser/load
When I remove the code of the modal from the code, the other parts of the UI work fine.
The view (settings.jsp):
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<jsp:include page="header_new.jsp"/>
<div class="page-title-area">
<div class="container-fluid">
<div class="row">
<div class="col-sm-11 col-sm-offset-1 page-title-section">
<h2 class="page-title">
<span>Settings</span>
</h2>
<ul class="page-title__nav common-list nav nav-tabs" style="margin-bottom: -5px">
<li <c:if test="${userTabActive}"> class="active" </c:if>><a data-toggle="tab"
onclick="loadUsers()">Users</a></li>
<li <c:if test="${roleTabActive}"> class="active" </c:if>><a data-toggle="tab"
onclick="loadRoles()">Roles</a></li>
</ul>
</div>
</div>
</div>
</div>
<script>
function loadUsers() {
window.location = '/admin/setting/systemUser/load';
}
function loadRoles() {
window.location = '/admin/setting/systemRole/load';
}
$(document).ready(function () {
$('#usersTable').DataTable({})
$('#rolesTable').DataTable({})
});
function loadUser(id) {
window.location = 'loadUser?id=' + id;
}
function loadRole(id) {
window.location = 'loadRole?id=' + id;
}
function deleteUser(id) {
$('#user-id').val(id);
$('#userDeleteModal').modal("show");
}
var checkPasswords = function () {
if (document.getElementById('password').value ==
document.getElementById('confirm-password').value) {
document.getElementById('passwordsMatchMessage').style.color = 'green';
document.getElementById('passwordsMatchMessage').innerHTML = 'Passwords are matching';
document.getElementById("submitButton").disabled = false;
} else {
document.getElementById('passwordsMatchMessage').style.color = 'red';
document.getElementById('passwordsMatchMessage').innerHTML = 'Passwords are not matching';
document.getElementById("submitButton").disabled = true;
}
}
</script>
<c:if test="${loadUserModal}">
<script>
window.alert("user edit modal");
$("#userSaveModal").modal()
document.getElementById('userModalLabel').innerHTML = 'Edit User';
document.getElementById('password').value = '';
</script>
</c:if>
<c:if test="${saveUser}">
<script>
window.alert("user save modal");
$("#userSaveModal").modal()
document.getElementById('userModalLabel').innerHTML = 'Save User';
</script>
</c:if>
<c:if test="${loadRoleModal}">
<script>
window.alert("role modal");
$("#roleSaveModal").modal()
document.getElementById('roleModalLabel').innerHTML = 'Save Role';
</script>
</c:if>
<!-- Begin page content -->
<div class="container-fluid">
<div class="row">
<jsp:include page="components/common/sidemenu.jsp">
<jsp:param name="activeTab" value="settings"/>
</jsp:include>
<div class="tab-content">
<div id="merchants" class="tab-pane fade active">
<c:if test="${errorView ne 'E1020'}">
<div class="col-md-11 col-md-offset-1">
<div class="page-card" style="padding-right: 20px;margin-left: 20px;margin-top: 20px">
</div>
</div>
</c:if>
</div>
</div>
</div>
</div>
<c:if test="${viewUsers}">
<div class="tab-content">
<div class="tab-pane fade in active">
<div class="container-fluid">
<div style="padding-top: 10px; padding-right: 20px">
<button type="button" class="btn btn-primary" style="float: right;" onclick="loadUser(0)"><i
class="fa fa-plus" style="margin-right: 5px"></i>New User
</button>
</div>
<div class="row">
<div class="col-md-11 col-md-offset-1">
<div class="page-card">
<div class="page-card__body">
<div class="table-responsive">
<table id="usersTable" class="table table-bordered table-striped dataTable">
<thead>
<tr>
<th>User Name</th>
<th>Name</th>
<th>Status</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.username}</td>
<td>${user.name}</td>
<td>${user.state}</td>
<td>${user.role.roleName}</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal"
onclick="loadUser('${user.id}')">
<i class="fa fa-edit"></i> Edit
</button>
<button type="button" data-toggle="modal" id="delete"
onclick="deleteUser('${user.id}')" name="delete"
class="btn btn-danger">
<i class="fa fa-trash-o"></i> Delete
</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</c:if>
<c:if test="${viewRoles}">
<div class="tab-content">
<div class="tab-pane fade in active">
<div class="container-fluid">
<div style="padding-top: 10px; padding-right: 20px">
<button type="button" class="btn btn-primary" style="float: right;" onclick="loadRole(0)"><i
class="fa fa-plus" style="margin-right: 5px"></i>Add Role
</button>
</div>
<div class="row">
<div class="col-md-11 col-md-offset-1">
<div class="page-card">
<div class="page-card__body">
<div class="table-responsive">
<table id="rolesTable" class="table table-bordered table-striped dataTable">
<thead>
<tr>
<th>Name</th>
<th>Permissions</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${roles}" var="role">
<tr>
<td>${role.roleName}</td>
<td>
<a href="#" data-toggle="popover" data-container="body"
data-content="<c:forEach var="permission" items="${role.permissionList}">
${permission.name}
</c:forEach>">View Permissions</a>
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal"
onclick="loadRole('${role.id}')">
<i class="fa fa-edit"></i> Edit
</button>
<%--<button type="button" class="btn btn-primary" data-toggle="modal"--%>
<%--onclick="editRole('${role.id}','${role.roleName}')" ><i class="fa fa-edit"></i> Edit--%>
<%--</button>--%>
<%--<button type="button" data-toggle="modal" id="delete"--%>
<%--onclick="deleteRole('${role.id}')" name="delete" class="btn btn-danger">--%>
<%--<i class="fa fa-trash-o"></i> Delete--%>
<%--</button>--%>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</c:if>
<div class="modal fade" id="userDeleteModal" tabindex="-1" role="dialog" aria-labelledby="userDeleteModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Delete Record</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you need to remove this record ?
</div>
<form id="systemUserDeleteForm" method="post" class="w3-margin" action="remove">
<input style="visibility: hidden !important;" id="user-id" name="id">
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Delete</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="userSaveModal" tabindex="-1" role="dialog" aria-labelledby="userSaveModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="col-md-4">
<h5 class="modal-title" id="userModalLabel"></h5>
</div>
<div class="col-md-8">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<div class="modal-body">
<form:form method="post" modelAttribute="user" action="save">
<div class="form-group">
<label class="col-form-label">User Name</label>
<form:input type="text" required="required" class="form-control" path="username"/>
<h6 class="fieldError"><form:errors path="username"/></h6>
</div>
<div class="form-group">
<label for="name" class="col-form-label">Name</label>
<form:input type="text" required="required" class="form-control" path="name"/>
<h6 class="fieldError"><form:errors path="name"/></h6>
</div>
<div class="form-group">
<label>Role</label>
<form:select class="form-control"
required="required" path="role.id">
<c:forEach items="${roles}" var="role">
<form:option value="${role.id}" label="${role.roleName}" />
</c:forEach>
</form:select>
</div>
<div class="form-group">
<label for="state">Status</label>
<form:select class="form-control"
required="required" path="state">
<form:option value="ACTIVE" label="ACTIVE"/>
<form:option value="INACTIVE" label="INACTIVE"/>
</form:select>
</div>
<c:if test="${saveUser}">
<div class="form-group">
<label class="col-form-label">Password</label>
<form:input onkeyup='checkPasswords();' type="password" class="form-control"
path="password"/>
<h6 class="fieldError"><form:errors path="password"/></h6>
</div>
<div class="form-group">
<label class="col-form-label">Confirm Password</label>
<input onkeyup='checkPasswords();' type="password" class="form-control" />
</div>
<span id='passwordsMatchMessage'></span>
</c:if>
<c:if test="${not saveUser}">
<%--hidden input value is passed for editing record to avoid getting a null value for the password for user object--%>
<form:input type="hidden" path="password"/>
</c:if>
<form:input type="hidden" name="id" path="id"/>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="submitButton" class="btn btn-primary">Submit</button>
</div>
</form:form>
</div>
</div>
</div>
</div>
<div class="modal fade" id="roleSaveModal" tabindex="-1" role="dialog" aria-labelledby="roleSaveModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="col-md-4" style="float: left">
<h5 class="modal-title" id="roleModalLabel"></h5>
</div>
<div class="col-md-8">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<div class="modal-body">
<form:form method="post" modelAttribute="role" action="save">
<div class="form-group">
<label for="role-name" class="col-form-label">Role Name</label>
<form:input type="text" required="required" class="form-control" id="role-name"
path="roleName"/>
<h6 class="fieldError"><form:errors path="roleName"/></h6>
</div>
<div class="form-group">
<label class="col-form-label">Permissions</label>
<c:forEach items="${permissions}" var="permission">
<div class="check-box" style="padding-left: 20px">
<c:choose>
<c:when test="${permission.checked}">
<form:checkbox value="${permission.id}"
path="checkedPermissions" checked="checked"/>
<label style=" margin-left: 10px">${permission.name}</label>
</c:when>
<c:otherwise>
<form:checkbox value="${permission.id}"
path="checkedPermissions"/>
<label style=" margin-left: 10px">${permission.name}</label>
</c:otherwise>
</c:choose>
</div>
</c:forEach>
</div>
<form:input type="hidden" id="id" name="id" path="id"/>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form:form>
</div>
</div>
</div>
</div>
The users controller :
#Controller
#RequestMapping("/setting/systemUser")
public class SystemUserController {
private final static Logger logger = LoggerFactory.getLogger(SystemUserController.class);
#Autowired
#Qualifier("systemUserValidator")
private Validator validator;
#Autowired
private SystemUserService systemUserService;
#Autowired
private SystemRoleService systemRoleService;
#Autowired
private UserDetailsHelper userDetailsHelper;
#InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
#RequestMapping(value = "/load", method = RequestMethod.GET)
public String viewRoles(Model model) {
loadData(model);
return "settings";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(Model model, #Validated #ModelAttribute("user") SystemUser user, BindingResult result) {
logger.info("User save/update request received [{}]", user.toString());
if (result.hasErrors()) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("roles", systemRoleService.getAllUserRoles());
model.addAttribute("loadUserModal", true);
return "settings";
}
systemUserService.saveSystemUser(user);
loadData(model);
return "settings";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String deleteRole(Model model, #RequestParam("id") Long id) {
SystemUser user = systemUserService.getSystemUser(id);
logger.info("User remove request received [{}]", user.toString());
systemUserService.deleteUser(user);
loadData(model);
return "settings";
}
#RequestMapping(value = "/loadUser", method = RequestMethod.GET)
public String loadUser(Model model, #RequestParam("id") Long id) {
loadData(model);
model.addAttribute("user", systemUserService.getSystemUser(id));
model.addAttribute("loadUserModal", true);
if (id == 0){
model.addAttribute("saveUser", true);
}
model.addAttribute("userTabActive", true);
model.addAttribute("viewUsers", true);
return "settings";
}
private void loadData(Model model) {
model.addAttribute("userDetails", userDetailsHelper.getSystemUser().getUsername());
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("roles", systemRoleService.getAllUserRoles());
model.addAttribute("user", new SystemUser());
model.addAttribute("userTabActive", true);
model.addAttribute("viewUsers", true);
}
}
The roles controller :
#Controller
#RequestMapping("/setting/systemRole")
public class SystemRoleController {
#Autowired
#Qualifier("systemRoleValidator")
private Validator validator;
#Autowired
private SystemRoleService roleService;
#Autowired
private UserDetailsHelper userDetailsHelper;
#InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
#RequestMapping(value = "/load", method = RequestMethod.GET)
public String viewRoles(Model model) {
loadData(model);
return "settings";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveRole(Model model, #Validated #ModelAttribute("role") SystemRole role, BindingResult result) {
logger.info("Role save/update request received [{}]", role.toString());
if (result.hasErrors()) {
model.addAttribute("roles", roleService.getAllUserRoles());
model.addAttribute("permissions", roleService.getAllPermission());
model.addAttribute("loadRoleModal", true);
return "settings";
}
roleService.saveSystemRole(role);
loadData(model);
return "settings";
}
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String deleteRole(Model model, #RequestParam("id") Long id) {
roleService.deleteRole(roleService.getUserRole(id));
loadData(model);
return "settings";
}
#RequestMapping(value = "/loadRole", method = RequestMethod.GET)
public String loadRole(Model model, #RequestParam("id") Long id) {
loadData(model);
model.addAttribute("loadRoleModal", true);
model.addAttribute("role", roleService.getUserRole(id));
SystemRole role = roleService.getUserRole(id);
model.addAttribute("permissions", roleService.getAllPermission(role));
return "settings";
}
private void loadData(Model model) {
model.addAttribute("roles", roleService.getAllUserRoles());
model.addAttribute("permissions", roleService.getAllPermission());
model.addAttribute("role", new SystemRole());
model.addAttribute("userDetails", userDetailsHelper.getSystemUser().getUsername());
model.addAttribute("roleTabActive", true);
model.addAttribute("viewRoles", true);
}
}
SystemRole model class :
#Entity(name = "system_user_role")
public class SystemRole implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "name")
private String roleName;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
#JoinTable(name = "system_role_permission", joinColumns = {
#JoinColumn(name = "id", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "permission_id", nullable = false)})
private List<Permission> permissionList = new ArrayList<Permission>();
#Transient
private List<Long> checkedPermissions = new ArrayList<>();
public SystemRole() {
}
The HTML views (when the modals are removed):
This doesnt seem to load when the modal are added. And the delete modal seems to work fine. What could be going wrong in here?

Unable to do spring form submission

Hi I am new to spring MVC, and unable to do form submission.
My Jsp Code
<form:form method="POST" action="save" commandName="report">
<div id="collapseOne" class="panel-collapse collapse in"
role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<div class="col-md-3 col-sm-12 col-xs-12 form-group" >
<label><spring:message code="label.report.report_type"/><span class="required">*</span></label>
<form:select id="reportTypeSelect" class="form-control" path="reportType">
<form:options items="${report.reportTypes}"></form:options>
</form:select>
<!-- <select
class="form-control" name="scheduleType">
<option><spring:message code="label.report.chose_type"/></option>
<option><spring:message code="label.report.adhoc"/></option>
<option><spring:message code="label.report.scheduled"/></option>
</select> -->
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">
<spring:message code="label.report.sql_query"/></label>
<div class="col-md-9 col-sm-9 col-xs-12">
<form:textarea class="resizable_textarea form-control"
placeholder="Write Sql Queries to exceute the records ..." name="query" path="reportQuery"></form:textarea>
</div>
</div>
<div class="col-md-3 col-sm-12 col-xs-12 form-group">
<label><spring:message code="label.report.query_name"/><span class="required">*</span></label>
<form:input type="text" placeholder="Query Name" name="reportQueryName" path="reportType" class="form-control"></form:input>
</div>
<div class="col-md-3 col-sm-12 col-xs-12 form-group">
<label><spring:message code="label.report.schedule_date"/><span class="required">*</span></label> <input
id="eventDate"
class="date-picker form-control col-sm-12 col-xs-12"
required="required" type="text">
</div>
<div class="col-md-6 col-sm-12 col-xs-12 form-group">
<label><spring:message code="label.report.emailid"/><span class="required">*</span></label> <form:input
type="text" placeholder="Maximum 4 Email Recepients" name="email" path="emails" class="form-control"></form:input>
</div>
<div class="clearfix"></div>
<div class="form-group">
<div class="button-right">
<!--<button type="submit" class="btn btn-primary">Save</button>-->
<button type="submit" class="btn btn-success"> <spring:message code="label.button.save"/>
</button>
</div>
</div>
</div>
</div>
</form:form>
My Controller
#Controller
public class ReportsViewController {
private static final Logger logger = LoggerFactory.getLogger(ReportsViewController.class);
#RequestMapping(value="/reports",method=RequestMethod.GET)
public String displayReports(ModelMap model) {
logger.info("Start of displayReports()...............");
ReportsViewBean report = new ReportsViewBean();
report.setReportTypes(getReportType());
model.addAttribute("report", report);
logger.info("End of displayReports()...............");
return "reportsView";
}
#RequestMapping(value="/reports/save",method=RequestMethod.POST)
public String updateReports(#ModelAttribute("query") String query) {
System.out.println("username" + query);
return "reportsView";
}
private List<String> getReportType() {
List<String> type = new ArrayList<String>();
type.add("Adhoc");
type.add("Schedule");
return type;
}
}
Your problem is here :
#RequestMapping(value="/reports/save",method=RequestMethod.POST)
public String updateReports(#ModelAttribute("query") String query)
This should be :
#RequestMapping(value="/reports/save",method=RequestMethod.POST)
public String updateReports(#ModelAttribute("report") ReportsViewBean report)
This is the only way to get your model after the POST and then you can retrieve the attribute's values of your model.
You don't add the code of your model but be sure that it has all attributes you put in each path attribute of your form.

How to separate 2 POST and 2 GET method in 1 controller class in spring mvc

i am developing web app that have a transaction for buying a product and that transaction required a customer data. so in that transaction form, i add a modal form for user to add a new customer data.
here currently it's look like :
link to open the add new customer modal form
modal form to add customer
And here my full controller class :
#Controller
public class InvoiceProductController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private MsEmployeeService msEmployeeService;
#Autowired
private MsCustomerService msCustomerService;
#Autowired
CustomerFormValidator customerFormValidator;
#Autowired
private MsLocationService msLocationService;
#Autowired
private MsReligionService msReligionService;
// Set a form validator
#InitBinder("msCustomer")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(customerFormValidator);
}
#RequestMapping(value = "/trproduct", method = RequestMethod.GET)
public ModelAndView trproduct(Locale locale, HttpSession session) {
ModelAndView mav = new ModelAndView("entryinvoiceproduct");
MsUser loggedInUser = (MsUser) session.getAttribute("loggedInUser");
List<MsEmployee> msEmployee = msEmployeeService.findEmployeeByJobsAndLocation("BEAUTY CONSULTANT",
(short) loggedInUser.getMsLocation().getId());
List<MsCustomer> msCustomer = msCustomerService.findAll();
mav.addObject("listCustomer", msCustomer);
mav.addObject("beautyConsultant", msEmployee);
mav.addObject("defaultLocation", loggedInUser);
return mav;
}
#RequestMapping(value = "/trproduct", method = RequestMethod.POST)
public String saveCustomer(#ModelAttribute("customerForm") #Validated MsCustomer msCustomer, BindingResult result,
Model model, final RedirectAttributes redirectAttributes) {
logger.debug("saveOrUpdateUser() : {}", msCustomer);
if (result.hasErrors()) {
populateDefaultModel(model);
return "/trproduct";
} else {
// Add message to flash scope
redirectAttributes.addFlashAttribute("css", "success");
if (msCustomer.isNew()) {
redirectAttributes.addFlashAttribute("msg", "User added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "User updated successfully!");
}
msCustomerService.persist(msCustomer);
// POST/REDIRECT/GET
return "/trproduct";
// POST/FORWARD/GET
// return "user/list";
}
}
// show add customer form
#RequestMapping( method = RequestMethod.GET)
public String showAddCustomerForm(Model model, HttpSession session) {
logger.debug("showAddCustomerForm()");
MsCustomer msCustomer = new MsCustomer();
MsUser loggedInUser = (MsUser) session.getAttribute("loggedInUser");
msCustomer.setUpdateUserId(loggedInUser.getId());
msCustomer.getMsLocation().setId(loggedInUser.getMsLocation().getId());
model.addAttribute("customerForm", msCustomer);
populateDefaultModel(model);
return "";
}
private void populateDefaultModel(Model model) {
List<MsLocation> msLocation = msLocationService.findAll();
model.addAttribute("locationList", msLocation);
List<MsReligion> msReligion = msReligionService.findAll();
model.addAttribute("religionList", msReligion);
}
}
and here my jsp, that calling the modal form in it :
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- CSS -->
<link href='<c:url value="/resources/datatables/datatables.css" />'
rel="stylesheet">
<script src="<c:url value="/resources/datatables/datatables.js" />"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#invoicedtls').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
$('#invoicepayments').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
$('#existingcustomer').DataTable({
"pageLength" : 8,
"lengthMenu" : [ 8, 16, 32, 64, 100 ],
select : true
});
// $("body").on("click", ".use-address", function() {
// var id = $(this).closest("tr").find(".custid").text();
// var name = $(this).closest("tr").find(".custname").text();
// alert(id + " , " + name);
// });
});
</script>
<div class="panel panel-default">
<div class="panel-heading">
<h4>Invoice Header</h4>
</div>
<div class="panel-body">
<form role="form">
<div class="col-lg-4">
<label>Customer :</label>
<div class="input-group">
<input type="text" class="form-control text-uppercase">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle"
data-toggle="dropdown">
Customer <span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right">
<li><a data-toggle="modal" data-target="#modalNewCustomer">New</a></li>
<li><a data-toggle="modal"
data-target="#modalExistingCustomer">Existing</a></li>
</ul>
</div>
<!-- /btn-group -->
</div>
<!-- /input-group -->
</div>
<div class="col-lg-3">
<label>Beauty Consultant :</label> <select id="disabledSelect"
class="form-control">
<option value="-1">Select a Beauty Consultant</option>
<c:forEach items="${beautyConsultant}" var="bc">
<option value="${bc.id}">${bc.name}</option>
</c:forEach>
</select>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-group pull-right">
<button class="btn btn-primary pull-right">Add New Product</button>
</div>
<h4>Product List</h4>
</div>
<div class="panel-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="invoicedtls" class="display highlight">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Qty</th>
<th>Discount Value</th>
<th>Discount Percent</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-group pull-right">
<button class="btn btn-primary pull-right">Add New Payment</button>
</div>
<h4>Payment List</h4>
</div>
<div class="panel-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="invoicepayments" class="display highlight">
<thead>
<tr>
<th>Pay With</th>
<th>Bank Name</th>
<th>Cardholder Name</th>
<th>Card No</th>
<th>Card Expired</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!-- Modal Existing Customer -->
<div class="modal fade" id="modalExistingCustomer" tabindex="-1"
role="dialog" aria-labelledby="modalExistingCustomerLabel">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalExistingCustomerLabel">Select
Existing Customer</h4>
</div>
<div class="modal-body">
<!-- <table class="table table-striped table-hover"> -->
<table id="existingcustomer" class="display compact">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Sex</th>
<th>Origin</th>
<th>Religion</th>
<th>Option</th>
</tr>
</thead>
<tbody>
<c:forEach var="customer" items="${listCustomer}">
<tr>
<td class="custid">${customer.id}</td>
<td class="custname">${customer.firstName}</td>
<td>${customer.sex}</td>
<td>${customer.msLocation.name}</td>
<td>${customer.msReligion.name}</td>
<td>
<button class="btn btn-link btn-xs use-address">Use</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Select
Customer</button>
</div>
</div>
</div>
</div>
<!-- Modal New Customer -->
<div class="modal fade" id="modalNewCustomer" tabindex="-1"
role="dialog" aria-labelledby="modalNewCustomerLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="modalNewCustomerLabel">Entry New
Customer</h4>
</div>
<div class="modal-body">
<form id="newCustomer" role="form" action="/admin/users/update" method="post">
<input id="id" name="id" placeholder="Id" value="0" type="hidden"
value="0" />
<div class="form-group">
<label for="firstName">First Name:</label> <input id="firstName"
name="firstName" placeholder="First Name" class="form-control"
type="text" value="" />
</div>
<div class="form-group">
<label for="lastName">Last Name:</label> <input id="lastName"
name="lastName" placeholder="Last Name" class="form-control"
type="text" value="" />
</div>
<div class="form-group">
<label for="email">Email:</label> <input id="email" name="email"
placeholder="Email" class="form-control" type="text" value="" />
</div>
<div class="form-group">
<label for="password">Password:</label> <input id="password"
name="password" placeholder="Password" class="form-control"
type="text" value="" />
</div>
<!-- /.modal-content -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save Customer</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// For demo to fit into DataTables site builder...
$('#invoicedtls').removeClass('display').addClass(
'table table-striped table-hover');
$('#invoicepayments').removeClass('display').addClass(
'table table-striped table-hover');
$('#existingcustomer').removeClass('display').addClass(
'table table-striped table-hover table-compact');
// Jquery draggable
$('.modal-dialog').draggable({
handle : ".modal-header"
});
</script>
What i am confusing is, when using a modal form, in controller class, i cannot separate the #RequestMapping value, because the value will always "/trproduct". In this controller class, i want to save 2 different table (SlInvoiceHdr and MsCustomer), but with the same #RequestMapping value.
I am using the same jsp for the add customer modal.
How can i do it in my controller ?
Thank You
Add the expected parameter to your request mapping
#RequestMapping( method = RequestMethod.GET , params = { "expectedparam" })
1 controller, 2 methods with the same requestMapping, but with different parameters
#RequestMapping(value = "/trproduct", method = RequestMethod.GET) public ModelAndView trproduct(Locale locale, HttpSession session) {
second:
#RequestMapping( method = RequestMethod.GET, params = { "newform" }) public String showAddCustomerForm(Model model, HttpSession session) {
But you have to add the the parameter "newform" to your url, like /trproduct?newform=true

Resources