I need choose values from one array and assign it to other array. Using Spring Thymeleaf. No idea how retrieve these choosed values.
My classes:
#Entity
public class Collaborator {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size (min=3, max=32)
private String name;
#NotNull
#ManyToOne (cascade = CascadeType.ALL)
private Role role;
public Collaborator() {}...
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 3, max = 99)
private String name;
public Role() {}....
My controllers:
#RequestMapping("/project_collaborators/{projectId}")
public String projectCollaborators(#PathVariable Long projectId, Model model) {
Project project = mProjectService.findById(projectId);
List<Collaborator> allCollaborators = mCollaboratorService.findAll();
List<Collaborator> assignments = new ArrayList<>();
if (project.getRolesNeeded()!=null) {
for (int i=0;i<project.getRolesNeeded().size();i++) {
assignments.add(new Collaborator("Unassigned", project.getRolesNeeded().get(i)));
assignments.get(i).setId((long) 0);
}
}
model.addAttribute("assignments", assignments);
model.addAttribute("allCollaborators", allCollaborators);
model.addAttribute("project", project);
return "project_collaborators";
}
#RequestMapping(value = "/project_collaborators/{projectId}", method = RequestMethod.POST)
public String projectCollaboratorsPost(#ModelAttribute Project project, #PathVariable Long projectId, Model model) {
Project p = mProjectService.findById(projectId);
//mProjectService.save(project);
return "redirect:/project_detail/{projectId}";
}
And template:
<form th:action="#{'/project_collaborators/' + ${project.id}}" method="post" th:object="${project}">
<label th:text="'Edit Collaborators: ' + ${project.name}">Edit Collaborators: Website Project</label>
<ul class="checkbox-list">
<li th:each="a : ${assignments}">
<span th:text="${a.role.name}" class="primary">Developer</span>
<div class="custom-select">
<span class="dropdown-arrow"></span>
<select th:field="${a.id}">
<option th:each="collaborator : ${allCollaborators}" th:value="${collaborator.id}" th:text="${collaborator.name}">Michael Pemulis</option>
</select>
</div>
</li>
</ul>
<div class="actions">
<input type="submit" value="Save" class="button"/>
Cancel
</div>
</form>
As you can see I want to let user choose for each role (roleNeeded) any collaborator from (allCollaborators) and keep that assigns in List (assignments).
And I get error message:
ava.lang.IllegalStateException: Neither BindingResult nor plain target
object for bean name 'a' available as request attribute
So question is: how to solve it, assign values from one array to another in template and retrieve that values in my controller.
The cause of the exception
The IllegalStateException you are getting is because th:field="${a.id}" in your select element must be related to the form th:object="${project}" element; the th:field attribute must refer to an actual field in the project instance (also you need to write th:field="*{fieldName}"). That should fix the exception you are getting, but will not solve your entire problem as the second part of it is related to how to make the values get into your controller, which I will explain next.
Sending the values to your controller
To get the values into your controller you will need to make a few changes. As I don't really know the code of your Project class, I will change a few things so you will be able to figure it out how to adapt this simple example to your particular case.
First, I understand you want to make a relation like the following in your form:
Role1 => CollaboratorA
Role2 => CollaboratorB
Your controller needs to receive a list and in order to receive this information we need two classes:
The class which will be storing the individual element data, mapping a role id with the collaborator id:
public class RoleCollaborator {
private Long roleId;
private Long collaboratorId;
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getCollaboratorId() {
return collaboratorId;
}
public void setCollaboratorId(Long collaboratorId) {
this.collaboratorId = collaboratorId;
}
}
A wrapper class to store a list of individual mappings:
public class RolesCollaborators {
private List<RoleCollaborator> rolesCollaborators;
public List<RoleCollaborator> getRolesCollaborators() {
return rolesCollaborators;
}
public void setRolesCollaborators(List<RoleCollaborator> rolesCollaborators) {
this.rolesCollaborators = rolesCollaborators;
}
}
The next thing to do is change your controllers where you have two methods, one that handles GET requests and another one which handles the POST requests and so, receives your form data.
In the GET one:
public String projectCollaborators(#PathVariable Long projectId, Model model) {
(... your code ...)
model.addAttribute("project", project);
// Add the next line to add the "rolesCollaborators" instance
model.addAttribute("rolesCollaborators", new RolesCollaborators());
return "project_collaborators";
}
As you can see, we added a line that will be used by the thymeleaf template. Right now is a wrapper of an empty list of roles and collaborators, but you can add values if you need to edit existing mappings instead of adding new ones.
In the POST one:
// We changed the #ModelAttribute from Project to RolesCollaborators
public String projectCollaboratorsPost(#ModelAttribute RolesCollaborators rolesCollaborators, #PathVariable Long projectId, Model model) {
(... your code ...)
}
At this point, your controller is prepared to receive the information sent from your form, that we also need to modify.
<form th:action="#{'/project_collaborators/' + ${project.id}}" method="post" th:object="${rolesCollaborators}">
<label th:text="'Edit Collaborators: ' + ${project.name}">Edit Collaborators: Website Project</label>
<ul class="checkbox-list">
<li th:each="a, stat : ${assignments}">
<span th:text="${a.role.name}" class="primary">Developer</span>
<div class="custom-select">
<input type="hidden" th:id="rolesCollaborators[__${stat.index}__].roleId" th:name="rolesCollaborators[__${stat.index}__].roleId" th:value="${a.role.id}" />
<span class="dropdown-arrow"></span>
<select th:field="*{rolesCollaborators[__${stat.index}__].collaboratorId}">
<option th:each="collaborator : ${allCollaborators}" th:value="${collaborator.id}" th:text="${collaborator.name}">Michael Pemulis</option>
</select>
</div>
</li>
</ul>
<div class="actions">
<input type="submit" value="Save" class="button"/>
Cancel
</div>
</form>
Here there are a few changes:
As I pointed out in The cause of the exception you need to change th:object="${project}" to th:object="${rolesCollaborators}", as rolesCollaborator is the instance name from where you will receive the values from your GET controller method and where you will be sending the values to your POST controller method.
I added a hidden input; this input will store the role id that will be send in association to the collaborator id the user picks from the interface using the select element. Take a look at the syntax used.
I changed the th:field value of your select element to refer to a field in the rollesCollaborators object we use in th:object="${rolesCollaborators}" form attribute. This will set the value of the collaborator in the RoleCollaborator element of the RolesCollaborators wrapped list.
With these changes your code will work. Of course, you can improve it with some other modifications, but I tried to not introduce more modifications to focus on your problem.
Related
I would like someone to help me on how to update row with entity manager. Here is a table ex, in angular where data is sent to rest service:
app.html
<tr *ngFor="let myCar of cars$ | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
<td>{{ (p - 1) * count + i + 1 }}</td>
<td>{{myCar.name}}</td>
<td>{{myCar.price}}</td>
<td><button type="submit" class="btn btn-secondary" (click)="fillForm(myCar)">
<i class="glyphicon glyphicon-edit"></i>Edit
</button></td>
</tr>
carsDTO.java
#Id
#Column(name = "name")
private String name;
#Column(name = "price")
private String price;
service.java
public carsDTO updateCar(carDTO cars){
TypedQuery<myquerycalss> query = entitymanager.createNamedQuery("sqlName",
myquerycalss.class);
// I need help to complete this update method
// Maybe no need to first find by id, the row gets update based on #id
// on the name
}
resource.java
#PUT
#Path("/updatecars")
public Response updateCar(){
// no preblem here
}
Note: You can see that in the app.html I have ID generated but my jave class just name and price variables.
What is the best approach to update a chosen entity, that is, fields of database record, in my service.java? My resouces url is without parameter, that is URL: .../updatecars
Your resource needs to receive the car selected and changed in the frontend.
You can change it to receive inside the request body, using this:
#RequestMapping(method = RequestMethod.PUT, value = "/updatecars")
public Response updateCar(#RequestBody() carDTO car){
// here you call the service, passing the car as parameter
service.updateCar(car);
}
Inside your angular component, you have to put the car selected in the http request. Something like this:
saveCar(car: carDTO){
return this.httpBase.put(this.url, car, this.options)
.map(dados => dados.json()); // handle the return here....
}
Inside your service:
public carsDTO updateCar(carDTO cars) {
TypedQuery<myquerycalss> query = entitymanager.createNamedQuery("sqlName", myquerycalss.class);
query.setParameter("name", cars.getName());
query.setParameter("price", cars.getPrice());
query.executeUpdate();
...
}
I'm assuming that your named query SQL is like this:
UPDATE cars SET price = :price WHERE name = :name
I'm trying to create a list of objects from form inputs. The objects are the same but their values may differ, it's essentially a menu.
I'm still getting to grips with Spring/Thymeleaf which is adding some level of complexity to what feels like a simple task.
I've a class for the menu, a simple POJO, there is then a list of these defined as a data member in the bean itself:
private ArrayList<GuestMenuOptions> guestMenus;
I've read many posts, tried many things and am on the verge of softly resting my head against the table.
I've had several errors, most of which either tell me that the list cannot be found or that the list is empty - it's currently in stable condition where the list, no matter what I try, will not be populated, even when I load in default values...unfortunately my debugger has died which is not helping.
Any help is appreciated. thank you
EntryController:
#RequestMapping(method=RequestMethod.GET, value="/")
public String indexPage(Model model) {
model.addAttribute("childMenuOptions", generateChildMenus());
//not sure if this is neccesary...
ArrayList<GuestMenuOptions>guestMenus = new ArrayList<>();
GuestMenuOptions ad1 = new GuestMenuOptions();
GuestMenuOptions ad2 = new GuestMenuOptions();
guestMenus.add(ad1);
guestMenus.add(ad2);
GuestContactBean ctb = new GuestContactBean();
ctb.setGuestMenus(guestMenus);
model.addAttribute("guestContactBean", ctb);
model.addAttribute("formBackingBean", new FormBackingBean());
return "index";
}
Form:
<form modelAttribute="guestBean" class="contact_form" name="rsvp" role="form" th:object="${formBackingBean}" th:action="#{/sendRsvp}" method="post">
<div class="row">
<div class="form-group">
<select name="ad1Starter" id="starterMealAdult1">
<option value="!!!">-Starter-</option>
<option th:field="${guestContactBean.guestMenus[0].starter}" th:each="entry : ${adultMenuOptions.get('starter').entrySet()}" th:value="${entry.key}" th:text="${entry.value}">
</option>
</select>
</div>
<input type="submit"guest name="submit" class="btn default-btn btn-block" value="Send RSVP">
RequestController:
#RequestMapping(value = "/sendRsvp", method = RequestMethod.POST)
public String sendRsvp(#ModelAttribute("guestContactBean") GuestContactBean guestContactBean,
#ModelAttribute("guestMenus") ArrayList<GuestMenuOptions>menus,
BindingResult result) throws MessagingException {
smtpMailSender.send(guestContactBean);
return "thanksMessage";
}
Beans:
FormBacking is POJO with no reference to the menus at all.
GuestMenuOptions is the same with just starter, desert members
guestContactbean has not much more going on, basic fields with the addition of the list of GuestMenuOptions
private String numberOfAdults;
private String eventAttending;
private ArrayList<GuestMenuOptions> guestMenus;
public ArrayList<GuestMenuOptions> getGuestMenus() {
return guestMenus;
}
EDIT:
The field that populates the drop downs in working fine, it's declared as private Map<String, Map<String, String>> adultMenuOptions;
private Map<String, Map<String, String>> childMenuOptions;
they are then built in the controller so that each may have several options under 'starter', 'main' and desert' for example:
starter.put("salmon", "Smoked Salmon");
starter.put("pate", "Chicken Liver Pate");
this is then populating both the value and text of the dropdown.
If I could save the state of this Map and pass it back to the controller instead, that would also be fine but I wasn't able to why then spawned the creation of the there wrapper list.
Please revisit http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dropdownlist-selectors. It should be as simple as
class Animal {
int id;
String name;
}
then in your template:
<select th:field="*{animalId}">
<option th:each="animal : ${animals}"
th:value="${animal.id}"
th:text="${animal.name}">Wireframe</option>
</select>
I think your code is all over the place and you're mixing up menu selection with menu item types.
I have issues in binding enum values in hidden fields with spring mvc.
The scenario is the following: I have a form with a list of documents which are characterized by a type.
My form class is (please note how the constructor is made. It fills the documents list with empty documents whose type is taken from the DocumentType enumeration):
public class Form {
private List<Document> documents = new ArrayList<Document>();
//while creating this class, I instantiate a number
//of empty documents with a certain type attribute
public Form() {
super();
for(DocumentType type : DocumentType.values())
{
Document document = new Document();
document.setType(type);
documents.add(document);
}
}
}
my document class is:
public class Document{
private DocumentType type;
private String expirationDate
private URL link
//getters & setters
}
while DocumentType is an ordinary enumeration
public enum DocumentType {
TYPE_A("type a"),
TYPE_B("type b"),
TYPE_C("type c");
private String literal;
public String getLiteral() {
return literal;
}
private StateDocumentType(String literal) {
this.literal = literal;
}
}
I want to display a form of this kind (the rounded boxes are form fields):
so, in order to update the right document with the proper link and expiration date, I want to use an hidden field associated to every form input row.
So my jsp is the following:
<form:form role="form" id="form" commandName="stateForm" action="${formUrl }">
<c:forEach items="${form.documents }" var="document" varStatus="vs">
<div id="doc_${document.type }>
<label>${document.type.literal }</label>
<div class="input-group">
<form:hidden path="documents[${vs.index }].type"/>
<form:input type="text" path="documents[${vs.index }].link"/>
</div>
</div>
<!-- omitted the exp. date part -->
</c:forEach>
</form:form>
here's the problem: when the html page is requested and rendered, the hidden field "value" attribute is just empty, while I expected it is valorized with the proper enum value. Please note that the parent <div> id is properly valorized. I really don't know why this doesn't work.
I'm new to Spring and I would like to get id and value of selected item of a dropdown. Here is a simple example
class MaritalStatus{
private int id;
private String status;
}
class regForm{
private MaritalStatus maritalStatus;
...
}
//Simple Controller to fill the list
#RequestMapping(value = "/save")
public String init(Model model){
List<MaritalStatus> maritalList = new ArrayList<MaritalStatus>();
maritalStatus.setId(1)
maritalStatus.setStatus("Married")
maritalList.add(maritalStatus);// add all status to the list....
model.addAttribute("maritalList",maritalList);
...
}
jsp page
<form:form commandName="regForm" action="save">
<form:select path="maritalStatus.id">
<form:options items="${maritalList}" itemValue="id" itemLabel="status" />
</form:select>
</form:form>
This is where I want to get selected item id and value (1 and Married)
#RequestMapping(value = "/save")
public String save(Model model,#ModelAttribute("regForm") RegForm regForm){
// here I want to get selected item Id and Status(Label)
//regFrom.getMaritalStatus().getId() and regFrom.getMaritalStatus().getStatus()
}
You can achieve it at least in 2 ways:
Send only the id of the selected MaritalStatus (you actually do it in your jsp), bind it directly to regForm.maritalStatusId and then (when you need it) get the MaritalStatus from the maritalList by the selected id (you have to keep the maritalList or create it somewhere, you do it anyway)
Bind your select directly to regForm.maritalStatus <form:select path="maritalStatus"> and write a specialized formatter that can convert from id to MaritalStatus object and vice versa. You'll find more information how to do it here: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/html/validation.html#format
[You could also send the id of the selected field and additionally its value in the hidden field and then try to build from those the MaritalStatus on the server side, but it is not elegant.]
You can get status by one hidden variable in jsp and a javascript function.
function changeStatus() {
var statusSelected = document.getElementById("maritalStatus");
var option = cookerModeIdSelected.options[statusSelected.selectedIndex];
var selectedValue = option.getAttribute("data-status");
document.getElementById("regForm").submit();
}
<form:form commandName="regForm" action="save">
<form:hidden id="maritalStatusValue" path="maritalStatusValue"/>
<form:select path="maritalStatus.id" id="maritalStatus">
<form:options items="${maritalList}" itemValue="id" itemLabel="status" data-status="${status}"/>
</form:select>
</form:form>
I want to save Village object through hibernate where already persisted District id need to be saved. I populated district object in dropdown. I coded similar work in spring 2, but in spring 3 it doesn't work.
here, if I log village.getDistrict() in POST, id is set perfectly as I set to dropdown but other value of district object is null.
#SessionAttributes({"village"})
#Controller
public class VillageController{
#Autowired(required=true)
private AddressService addressService;
#RequestMapping(value="/cp/village.html", method = RequestMethod.GET)
public String setForm(ModelMap model) {
Village village = new Village();
village.setDistrict(new District());
model.addAttribute("village", village);
return "/cp/village";
}
#ModelAttribute("districtList")
public List<District> populateDistrictList() {
return addressService.getDistrictList();
}
#RequestMapping(value="/cp/village.html", method = RequestMethod.POST)
public String getForm(#ModelAttribute("village") Village village,
BindingResult result,
SessionStatus status) {
log.debug("============================="+village.getDistrict());
addressService.saveVillage(village);
status.setComplete();
return "redirect:/cp/village.html123";
}
}
In JSP:
<form:form commandName ="village" action="village.html" >
<div>
<label><fmt:message key="location.district"/></label>
<form:select path="district.id">
<form:options items="${districtList}" itemValue="id" itemLabel="districtName"/>
</form:select>
</div>
<div>
<label><fmt:message key="location.village"/></label>
<form:input path = "villageName" />
</div>
<div>
<label><fmt:message key="prompt.remarks"/></label>
<form:textarea path = "remarks" rows="2" cols="50"/>
</div>
<div class = "button-area">
<input type = "submit" value="Save" class="submit-button" />
<input type = "button" value="Cancel" onclick="window.location='commonComplaintList.html'" class="submit-button" />
</div>
<br/>
</form:form>
You do not set any value in the District object, so it is empty.
If you expected that the district has the values of objects from List<District> populateDistrictList(), then I have to say: it does not work out of the box.
One way to do it, would be implementing a Converter, that converts a string (the id) to the District object, by loading it from the database.
I think you need to implement a Converter for the District entity as well. Since the Converter for your Village entity class is likely not called at all during the POST (at least not for new Villages, since they lack an id). Also, even if it was called the District would still need a Converter in order to fetch the correct District from Hibernate. Otherwise, Spring will just give you a fresh instance of the District with the Id set to the value in the select.
However, if you are only going to save the Village I am unsure whether you would actually need to fetch the whole District object from Hibernate. I think (not 100% sure on this since it was a while since I used Hibernate and Spring) that Hibernate will associate the village you create in your POST with the correct district even though you only have a District object with an Id. You might need to specify some annotation stuff about cascading for it to not overwrite the District objects other properties.
EDIT:
Looked it up a bit and I think you should annotate the district property of the Village class with something like:
#Column(name = "district", insertable = false)
That way Hibernate will know that no new districts should be added when storing a new Village.
Again not sure about this last part, but worth a quick try :)