Multiple similar forms in same page - spring-boot

In Spring Boot with Thymeleaf, I have a page that should handle two forms corresponding to a same model Person. Each form can be submitted separately, so I use two methods in the controller:
#PostMapping(value="/", params={"submitFather"})
public String submitFather(
#ModelAttribute("fatherForm") Person fatherForm,
#ModelAttribute("motherForm") Person motherForm,
Model model) {
// ... Process fatherForm
// Return the updated page
model.addAttribute("fatherForm", fatherForm);
model.addAttribute("motherForm", motherForm);
return "index.html";
}
#PostMapping(value="/", params={"submitMother"})
public String submitMother(
#ModelAttribute("fatherForm") Person fatherForm,
#ModelAttribute("motherForm") Person motherForm,
Model model) {
// ... Process motherForm
// Return the updated page
model.addAttribute("fatherForm", fatherForm);
model.addAttribute("motherForm", motherForm);
return "index.html";
}
In my template:
<form id="fatherForm" th:object="${fatherForm}" method="post">
<label for="firstName">First name</label>
<input type="text" th:field="*{firstName}"><br>
<!-- ... other Person fields -->
<input type="submit" name="submitFather" value="Order">
</form>
<form id="motherForm" th:object="${motherForm}" method="post">
<label for="firstName">First name</label>
<input type="text" th:field="*{firstName}"><br>
<!-- ... other Person fields -->
<input type="submit" name="submitMother" value="Order">
</form>
The issue I have is that this leads to HTML IDs clashes. There will be for example two <input> with id firstName. This causes invalid HTML and interference between the fields from the two forms when submitted.
One solution would be to have two models, Father and Mother with fields named such as fatherFirstName to ensure no duplicate HTML IDs. But this leads to substantial code duplication, and long and different field names (while only the HTML IDs need to be different).
How can this be solved? Is there a way to tell Spring to prefix ids with some string while ensuring I can still use the same Person model for the two forms?

Related

Thymeleaf: Partially set values to model object from outside the form tags

I have an model object that I send to front end. I populate that object inside the form. What I want to know is that if I can partially populate that object from a different event before user submits his/her form?
Example:
Entity:
public class Participant {
public String username;
public boolean taskCompleted;
}
Thymeleaf Form:
<form th:object="${participant}" th:action="#{/join}" method="post">
<input type="text" th:field="*{username}" >
<button type="submit">Join!</button>
</form>
Before submitting the form, I give users a task, like clicking a button on a different part of the page. If they do it, I want to do something like taskCompleted = true of the same participant object. Is that possible?
Use a hidden input in your form:
<form th:object="${participant}" method="post">
<input type="text" th:field="*{username}" >
<input type="hidden" th:field="*{taskCompleted}" />
<button type="submit">Join!</button>
</form>
When the user clicks a button, use JavaScript to set the value of the hidden input to true.
<!-- This button flips the value of taskCompleted to true -->
<button onclick="document.getElementById('taskCompleted').value = 'true';">Do the task first!</button>

Thymeleaf set default value [duplicate]

I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.
Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.
This should behave just like a standard "edit profile" page.
Here is a segment of my edit_profile.html page:
First Name:
Here is the view controller method that returns edit_profile.html page:
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEditProfilePage(Model model) {
model.addAttribute("currentUser", currentUser);
System.out.println("current user firstname: " + currentUser.getFirstname());
model.addAttribute("user", new User());
return "edit_profile";
}
currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.
Thanks.
Solved the problem by removing th:field altogether and instead using th:value to store the default value, and html name and id for the model's field. So name and id is acting like th:field.
I'm slightly confused, you're adding currentUser and a new'd user object to the model map.
But, if currentUser is the target object, you'd just do:
<input type="text" name="firstname" value="James" th:value="${currentUser.firstname}" />
From the documentation:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
I did not have a form with input elements but only a button that should call a specific Spring Controller method and submit an ID of an animal in a list (so I had a list of anmials already showing on my page). I struggled some time to figure out how to submit this id in the form. Here is my solution:
So I started having a form with just one input field (that I would change to a hidden field in the end). In this case of course the id would be empty after submitting the form.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
The following did not throw an error but neither did it submit the animalIAlreadyShownOnPage's ID.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
In another post user's recommended the "th:attr" attribute, but it didn't work either.
This finally worked - I simply added the name element ("id" is a String attribute in the Animal POJO).
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>

Using remote attribute in .net core razor pages. The Parameter does not get value in Action Method of Controller

I am using Remote Attribute validation
The method is invoked successfully on textchange event. However, the parameters in the action method of the controller does not get the value of the field.
Here is the Action Method in the HomeController.cs. When invoked the Name parameter remains null. I will be pleased if someone solve this problem
[AcceptVerbs("Get", "Post")]
public async Task<ActionResult> IsExist(string Name)
{
List<Keywords> keywords = new List<Keywords>();
HttpClient client = _api.Initial();
HttpResponseMessage res = await client.GetAsync("api/Keywords");
if (res.IsSuccessStatusCode)
{
var result = res.Content.ReadAsStringAsync().Result;
keywords = JsonConvert.DeserializeObject<List<Keywords>>(result);
}
if (keywords.FirstOrDefault(x => x.Name == Name) == null)
{
return Json(false);
}
else
{
return Json(true);
}}
Here is the Model
public partial class Keywords
{
public int Id { get; set; }
[Display(Name = "Name of Keyword")]
[Required]
[Remote(action: "IsExist",controller: "Home", ErrorMessage = "Keyword already present!")]
public string Name { get; set; }}
Here is the razor page in which I want to implement validation
#page
#model Consumer.Pages.Keyword.CreateModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Keywords</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Keywords.Name" class="control-label"></label>
<input asp-for="Keywords.Name" class="form-control" />
<span asp-validation-for="Keywords.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Keywords.Department" class="control-label"></label>
<select asp-for="Keywords.DepartmentId" class="form-control" asp-items="ViewBag.Department"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
I found the solution. It is to
Remove partial in the model class definition.
Replace in the Razor Page
<input asp-for="Keywords.Name" class="form-control" />
with
<input asp-for="Keywords.Name" name="Name" class="form-control" />
The [Remote] attribute is all but useless. There's a long-standing problem from the ASP.NET MVC days that migrated its way into ASP.NET Core unabated, as well. Namely, the action that handles the remote must take a param that matches the input name of what what's being validated. In other words, your action takes a param, name, but what's being sent to it is Keywords.Name, which cannot bind to name. You'd have to do something like:
public async Task<ActionResult> IsExist(Keywords keywords)
And then, then the value will be available via keywords.Name. This obviously makes the usage highly dependent on the particular implementation, so if there's a situation with a different input name like Foo.Keywords.Name, then you'd need an entirely different action, to match that binding, and basically duplicate the logic (though you could factor out the majority the logic into some common method all the actions could utilize).
Long and short, you're probably better off just handling this yourself manually. Just bind to the input event on the name input, and then call your method via AJAX. Then you can explicitly control the key that's sent in the request body, such that it will always match your action. Just note that you'll also want to debounce sending that AJAX request so that it only happens every few keystrokes or so. Otherwise, you're going to hammer your action.

handle one to many relationship in thymeleaf using spring mvc

I'm having One entity as Vendor and Another as Address and the relationship between both of them is One To Many form Vendor to Address.
Note : I am using JPA
My Vendor Entity
public class Vendor {
private Integer id;
private String name;
private List<Address> address;
// getter and setters
}
Address class:
public class Address {
private Integer id;
private String addressline1;
private String addressline2;
//getter and setters
}
Now I am using Thymeleaf , I have a scenario where I need to add the address dynamically to a form for the particular vendor.
How do I do Object binding for the Address object in Vendor using Thymeleaf in spring mvc?
Comment if i didn't understand your question correct, it's a bit unclear to me...
In order to access the address(s) of a vendor, you provide a vendor within your controller (something like model.addAttribute("vendor", currentVendor);) and call vendor.address in your html file. Please note that this will give you a list so you need to iterate to show all address:
<tr th:each="address : ${vendor.address}">
<td th:text="${address.id}">1</td>
<td th:text="${address.addressline1}"></td>
<td th:text="${address.addressline2}"></td>
</tr>
Uhhh, that's tricky because binding to form doesn't work in a dynamic way. That means you can't do something like #Viergelenker suggests AND bind each address-object to his own form.
You can add a single address object to the model, e.g.
model.addAttribute("address", addressObject); // Snippet for Model-object
modelAndView.addObject("address", addressObject); // Snippet for ModelAndView object
and then define a form in yout template like:
<form .... method=".." th:object="${address}">
<input type="hidden" th:field="*{id}" >
<input type="text" th:field="*{addressline1}" >
<input type="text" th:field="*{addressline2}" >
</form>
Unfortunately it is not possible to add a array or list to the model and bind each object in that collection to his own form:
/* The following code doesn't work */
<th:block th:each="address : ${addresses}">
<form .... method=".." th:object="${address}">
<input type="text" th:field="*{addressline1}" >
...
</form>
</th:block>
or
/* The following code doesn't work */
<th:block th:each="address, stat : ${addresses}">
<form .... method=".." th:object="${addresses[__stat.index__]}">
<input type="text" th:field="*{addressline1}" >
...
</form>
</th:block>
What you can do is not to use form binding and just send some name-value pairs from forms without the binding (just use the name and the th:value attributes and not the th:field attribute in your forms) to the controller, get them there from the HttpServletRequest object and create/update/delete address-objects ... or bind the whole Vendor object to a form (note the use of stat.index):
<form th:object="${vendor}">
<input type="hidden" th:field="*{id}">
<input type="hidden" th:field="*{name}"> // feel free to make that field editable
<th:block th:each="addr, stat : *{address}">
<input type="hidden" th:field="*{address[__${stat.index}__].id}">
<input type="text" th:field="*{address[__${stat.index}__].addressline1}">
<input type="text" th:field="*{address[__${stat.index}__].addressline2}">
</th:block>
</form>

how to intercept #modelattribute binding

Everyone.
I am using spring mvc framework, and spring form tag. I found unexpected thing when using form dynamically. For example,
public class Person {
public List<Car> myCars = new ArrayList<Car>();
// getter and setter
}
below code is html form
<form:form modelAttribute="car" ...>
<input type="hidden" name="myCars[0].id">
<input type="text" name="myCars[0].name">
<input type="hidden" name="myCars[1].id">
<input type="text" name="myCars[1].name">
<input type="hidden" name="myCars[2].id">
<input type="text" name="myCars[2].name">
</form:form>
and next code is a spring form controller
#Controller
#SessionAttribute({"car"})
public class CarController {
...
#RequestMapping(".....")
public String form(#ModelAttribute Car car, BindingResult result, ...) {
if (result.hasErrors()) {
....
return viewName;
}
....
return "redirect:/" + someWhere;
}
}
1) I entered data into html form.
2) I can confirm that there are 3 Car objects in car.getMyCars()
3) There are some errors as binding, so it's redirected to viewName
4) I changed html form using jQuery like this
<form:form modelAttribute="car" ...>
<input type="hidden" name="myCars[0].id">
<input type="text" name="myCars[0].name">
<input type="hidden" name="myCars[1].id">
<input type="text" name="myCars[1].name">
</form:form>
and, submit. The result of this test is that #ModelAttribue Car car still remains 3rd element in List myCars. I expected to remain 2 Car elements, but it wasn't. I think it remained in session. And it was overwritten new form data to #ModelAttribute Car car object, but last 3rd element wasn't. My test shows that if form elements increase dynamically, binding object using #ModelAttribute have them. But though decreased dynamically, binding object still have them. I hope that Car car object have accurate number of form inputs. What should I do?
Thanks in advance.

Resources