I have a Springboot & Thymeleaf project that is generating the same "names" on my person inputs.
The controller looks like:
#GetMapping("/newEpisode")
public String episodeForm(Model model) {
model.addAttribute("episode", new Episode());
List<Country> countries = countryRepository.findAll();
Set<String> roles = new HashSet<>();
roles.add("Admin");
model.addAttribute("primaryPerson1",new EpisodePerson());
model.addAttribute("primaryPerson2",new EpisodePerson());
model.addAttribute("roles", roles);
model.addAttribute("countries", countries);
return "episode";
}
Some of my HTML looks like:
<input type="text" class="form-control person surname" style="text-transform: uppercase" data-property="surname" placeholder="SURNAME" th:field="${primaryPerson1.person.surname}"/>
But the generated name in the HTML for this tag is not unique:
<input type="text" class="form-control person surname" style="text-transform: uppercase" data-property="surname" id="surname1" placeholder="SURNAME" name="person.surname" value="">
Why are all the person tags in the html sharing the same name for example I have two :
name="person.surname"
You've misused the th:field attribute.
Its aim is to bind your input with a property in the form-backing bean. So you should either create separate forms for each object and use it in following manner:
<!-- Irrelevant attributes omitted -->
<form th:object="${primaryPerson1}">
<input th:field="*{person.surname}"/>
</form>
...or create a form-backing bean, which would combine both of your objects, e.g.:
public class EpisodeFormBean {
private List<EpisodePerson> episodePersons;
//getter and setter omitted
}
...then add it to a model in your episodeForm method...
EpisodeFormBean episodeFormBean = new EpisodeFormBean();
episodeFormBean.setEpisodePersons(Arrays.asList(new EpisodePerson(), new EpisodePerson()));
model.addAttribute("episodeFormBean", episodeFormBean);
...and use it in your template as follow:
<!-- Irrelevant attributes omitted -->
<form th:object="${episodeFormBean}">
<input th:field="*{episodePersons[0].person.surname}"/>
<input th:field="*{episodePersons[1].person.surname}"/>
</form>
In the second solution generated names would be unique. I think it's more suitable for your needs.
You should check out Tutorial: Thymeleaf + Spring as there it is well explained. Especially you should notice a phrase:
Values for th:field attributes must be selection expressions (*{...}),
which makes sense given the fact that they will be evaluated on the
form-backing bean and not on the context variables (or model
attributes in Spring MVC jargon).
Related
I want to pass two objects from thymeleaf form to a controller. Here is my thymeleaf code :
<!DOCTYPE html>
<html lang='en' xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<title>Payment Page</title>
</head>
<body>
<h1>Payment List</h1>
<table>
<tr>
<th>StuId</th>
<th>Month</th>
<th>Amount</th>
</tr>
<tr th:each="payment:${student.payments}">
<td th:text="${student.id}">2</td>
<td th:text="${payment.month}">devesh</td>
<td th:text="${payment.amount}">23</td>
</tr>
</table>
<h3>Add a Payment</h3>
<form action="#" th:action= "#{/payments}" th:object="${payment}" method="POST">
<div th:object="${student}" >
<label for="name">Month:</label>
<input type="text" name="month" size="50"></input><br/>
<label for="amount">Amount:</label>
<input type="text" name="amount" size="50"></input><br/>
<input type = "submit"/></form>
</body>
</html>
in form except the payment object which is actually being submitted here , i want to pass student object or id to my controller as any payment should correspond to a particular student. i Could not find any way till now after searching a lot.
PaymentController method where i want to pass the objects , as i am using submit form , i could not pass variable in th:action
#RequestMapping(method = RequestMethod.POST, value = "/{id}/payments")
public String doPayment(#ModelAttribute("payment") PaymentRecord paymentRecord, #PathVariable int id) {
Student st = studentService.getStudentInfo(id);
st.addPayments(paymentRecord);
System.out.println("entered into do payment");
studentService.addStudent(st);
paymentService.doPayment(paymentRecord);
return "redirect:{id}/payments";
}
Please suggest. I am stuck here
You can do this different ways.
But first, let's shorten the post method annotation from:
#RequestMapping(method = RequestMethod.POST, value = "/{id}/payments")
to
#PostMapping("/{id}/payments")
I would also change the variable id to studentId to make it more clear for the next person reading your code.
Now, include the variable as a hidden input type within the form tags:
<input type="hidden" name="studentId" th:value="${student.id}">
Then you can either
a) Add a String studentId property to your PaymentRecord class. Then in the post method, you can call paymentRecord.getStudentId();
or
b) Add a request parameter for the studentId to your method mapped with #PostMapping. So your method signature can have #RequestParam(String studentId). In this case, the value of the studentId will be fully exposed to the user.
or
c) Use #RequestBody and map the values to a bean. You can read up on this topic further and look at some background with this question.
Instead of :
return "redirect:{id}/payments";
try this:
return "redirect:" + id + "/payments";
or (if need leading / in the redirect) :
return "redirect:/" + id + "/payments";
Of if you want to "GET" with multiple objs then you can something like:
#RequestMapping(value = { "/deleteuserdocument/{docid}/{userid}" }, method = RequestMethod.GET)
This is from my github repo where I am "GET"ting the documentid for a specific userid. Hope this might help.
How to return List of Objects to Backend Service? For E.g. there are list of customer getting displayed in UI, out of which only those customers which users selects (checks in checkbox) should be returned to the backend (Controller class). But i am not able to returned the selected object back.
My code:
public class CustomerType {
private String customerName;
private String customerMsg;
private Boolean selected;
// setter
// getter
}
public class Customers {
private ArrayList<CustomerType> customerType;
// setter
// getter
}
#GetMapping(value = "/")
public String index(ModelMap modelMap) {
ArrayList<CustomerType> customerType = new ArrayList<>();
customerType.add(new CustomerType("1", "c1", null));
customerType.add(new CustomerType("2", "c2", null));
customerType.add(new CustomerType("3", "c3", null));
Customers customers = new Customers();
customers.setCustomerTypes(customerType);
modelMap.put("customers", customers);
return "index";
}
#PostMapping(value = "/save")
public String save(#ModelAttribute Customers customers, BindingResult errors, Model model) {
...
...
return "hello";
}
========== index.html ==========
...
<form id = "form" class="col-xs-12 col-sm-4" role="form"
th:action="#{/save}" method="post" th:object="${customers}">
<div class="checkbox" th:each="customerType : ${customers.customerType}" >
<input type="checkbox" id="custType" name="custType"
th:text="${customerType.customerName}" th:value="${customerType.customerMsg}" th:checked="${customerType.selected}"></input>
</div>
<div>
<p>
<button type="submit" class="btn btn-default">Submit</button>
</p>
</div>
</form>
I am able to display lists of Customers on UI e.g there are three customer c1, c2, c3 out of which if user selects c1 and c3 so after clicking on submit button those should get mapped to #ModelAttribute Customers Object in save method and that object should contain list of two Objects c1 and c3, but instead of getting 2 Objects I am receiving Null.
I am not able to get where i am going wrong.
While sending your form back to controller, be sure that transmited data reflect desired object structure. You have to provide checkboxes that correspond the checked field of the CustomerType objects and additional hidden inputs which correspond others fields of mentioned class.
Please update your form to looks like:
<form id = "form" class="col-xs-12 col-sm-4" role="form" th:action="#{/save}" method="post" th:object="${customers}">
<div class="checkbox" th:each="customerType, iterator : ${customers.customerType}" >
<input type="hidden" th:field=*{customerType[__${iterator.index}__].customerName} />
<input type="hidden" th:field=*{customerType[__${iterator.index}__].customerMsg} />
<input type="checkbox" th:field="*{customerType[__${iterator.index}__].selected}" th:text="${customerType.customerName}" ></input>
</div>
<div>
<p>
<button type="submit" class="btn btn-default">Submit</button>
</p>
</div>
</form>
With this you'll receive the Customers object containing list of all passed CustomerType objects, with selected fields evaluated to true for checked records.
The name of the input fields in the form should match the property name in the CustomerType class i.e they should be customerName and customerMsg for the Spring to be able to create and populate the corresponding CustomerType object.
Using the MvcForm HtmlHelper, I have added 'id' and 'data-values' attributes to a form in an ASP.NET MVC Razor view.
I created a new object 'DataVars' to hold local and Model values. Then I converted 'DataVars' object into a JSON object and added it to the form tag 'data-values' attribute to be referenced later by JavaScript on the client-side.
#{
var DataVars = new
{
var1= LocalVar,
var2= Model.var1
};
var testing = Json.Encode(DataVars);
}
#using (Html.BeginRouteForm("GetForm", FormMethod.Get, new
{
id = "formId",
data_values = #Html.Raw(testing)
})) {
<div class="form-element-group">
<label class="screen-reader-only" for="terms">#T("Tooltip")</label>
<input type="text" class="text" id="terms" autocomplete="off" name="q" placeholder="#T("Tooltip")" />
<span class="input-group-btn">
<input type="submit" class="button" value="#T("Button")" />
</span>
</div>
}
This all works, but the problem is, in the resulting HTML output in the form 'data-values' attribute, double quotes are encoded within the JSON object;
data-values="{"var1":"text info","var2":0}"
When stepping through the code in debug the value for variable testing is set to:
{\"var1\":\"text info\",\"var2\":0}
Is there a way to force the JSON to be;
data-values="{"var1":"text info","var2":0}"
I have a Thymeleaf template in a simple Spring Boot application. The template contains a list in a table as follows:
<p>There are <span th:text="${#lists.size(persons)}"></span> people:</p>
<table th:if="${not #lists.isEmpty(persons)}" border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
<th>Email</th>
<th>Actions</th>
</tr>
<tr th:each="person : ${persons}">
<td th:text="${person.personId}"></td>
<td th:text="${person.name}"></td>
<td th:text="${person.address}"></td>
<td th:text="${person.telephone}"></td>
<td th:text="${person.email}"></td>
<td>
Edit |
Delete
</td>
</tr>
</table>
I want to enable edit and delete functionality as per the last cell in the table. But at the moment both requests are for HTTP GET. That is fine for edit where a person's details are fetched from the server for editing, but delete should trigger a POST request because of the data changes on the server.
Does anyone know if Thymeleaf allow a POST request per row of a table? Or do I have to write a simple HTML form per row?
The GET form is currently:
<td>
Edit
<!--a href="#" data-th-href="#{/delete(personId=${person.personId})}">Delete</a></td-->
<form method="get" th:action="#{/edit(personId=${person.personId})}">
<button type="submit" name="submit" value="value">Edit</button>
</form>
</td>
Where I have a link and a form for testing.
The controller method to be called is:
// Gets a Person.
#RequestMapping(value="/edit", method=RequestMethod.GET)
public String getEditPerson(#RequestParam("personId") String personId, Model model) {
logger.info(PersonController.class.getName() + ".getEditPerson() method called.");
Person person = personDAO.get(Integer.parseInt(personId));
model.addAttribute("person", person);
// Set view.
return "/edit";
}
The error when the button version of GET is called is:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Jul 24 00:26:16 BST 2016
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'personId' is not present`
I am using GET to trigger editing because no data is sent to the server here other than the personId. No database action is taken so it should be a GET.
you are using Links and I don't think that is possible, you would need to use a form where you can specify the method POST to be used.
In the example below im using a <button> instead of a <a> element, but it will work, the only thing you need to do is to style your button with CSS to look like your links
<form method="POST" th:action="#{/edit(personId=${person.personId})}">
<button type="submit" name="submit" value="value" class="link-button">This is a link that sends a POST request</button>
</form>
now in your code should look like this
<tr th:each="person : ${persons}">
<td th:text="${person.personId}"></td>
<td th:text="${person.name}"></td>
<td th:text="${person.address}"></td>
<td th:text="${person.telephone}"></td>
<td th:text="${person.email}"></td>
<td>
<form method="POST" th:action="#{/edit(personId=${person.personId})}">
<button type="submit" name="submit" value="value" class="link-button">EDIT</button>
</form> |
<form method="POST" th:action="#{/delete(personId=${person.personId})}">
<button type="submit" name="submit" value="value" class="link-button">DELETE</button>
</form>
</td>
</tr>
EDIT
As you just shared you Java code, in the controller you are expecting the personId not as a PathVariable, but as a RequestParam,
in that case your form should have that value...
edit your form and add the person id as follows.
<form method="POST" th:action="#{/edit}">
<input type="hidden" name="personid" id="personId" th:value="${person.personId}" />
<button type="submit" name="submit" value="value" class="link-button">This is a link that sends a POST request</button>
</form>
Notice also I changed the action of the form to be just /edit, as its what your controller looks like
Does anyone know if Thymeleaf allow a POST request per row of a table? Or do I have to write a simple HTML form per row?
HTML doesn't support POST request with links and you have to use forms (as Rayweb_on explained). But Thymeleaf allows you to define custom tags which helps a lot :
<a th:href="#{/edit(personId=${person.personId})}" custom:linkMethod="post">Edit</a>
... which would generate following HTML (assuming jQuery is available) :
Edit
Custom tag definition (without error checking to keep it simple) :
/**
* Custom attribute processor that allows to specify which method (get or post) is used on a standard link.
*/
public class LinkMethodAttrProcessor extends AbstractAttributeTagProcessor {
private static final String ATTR_NAME = "linkMethod";
private static final int PRECEDENCE = 10000;
public LinkMethodAttrProcessor(final String dialectPrefix) {
super(
TemplateMode.HTML, // This processor will apply only to HTML mode
dialectPrefix, // Prefix to be applied to name for matching
null, // No tag name: match any tag name
false, // No prefix to be applied to tag name
ATTR_NAME, // Name of the attribute that will be matched
true, // Apply dialect prefix to attribute name
PRECEDENCE, // Precedence (inside dialect's own precedence)
true); // Remove the matched attribute afterwards
}
#Override
protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IElementTagStructureHandler structureHandler) {
// get the method name (tag parameter)
final IEngineConfiguration configuration = context.getConfiguration();
final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
final IStandardExpression expression = parser.parseExpression(context, attributeValue);
final String method = (String) expression.execute(context);
// add custom javascript to change link method
final String link = tag.getAttribute("href").getValue();
final String action = "$('<form action="" + link + "" method="" + method + ""></form>').appendTo('body').submit(); return false;";
structureHandler.setAttribute("onclick", action);
structureHandler.setAttribute("href", "#");
}
}
See the Thymelead documentation for example of how this custom attribute needs to be registered.
I am creating a site in which I utilize partial views to display various bits of data about a single Model. Here is a bit of the HTML. (Note, all of these are contained within a single form and the Index page that these partials are rendered in is strongly typed to the main model. The main model contains various lists of data.)
<div id="tab1"><% Html.RenderPartial("Tab1", Model); %></div>
<div id="tab2"><% Html.RenderPartial("Tab2", Model.AnItemList1.FirstOrDefault<AnItemList1>()); %></div>
<div id="tab3"><% Html.RenderPartial("Tab3", Model.AnItemList2.FirstOrDefault()); %></div>
Here is ONE of the partial views headers (for 'tab2'):
<%# Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AnItem1>" %>
The pages display correctly. The issue is that, when I enter data into the various parts of the partial pages and then submit the entire form (via POST), the data is not making it back to my data store (MSSQL) - but this only happens for any of the list items (that are contained within the Model). The first partial page does properly have its data set within the data store.
What am I doing wrong here? Should I only be passing the model to Html.RenderPartial and then get the specific model I need on the partial page? Should I pass the entire list and then get the first (right now, I only care about the first item in the list - that will EVENTUALLY change, but not any time soon).
Suggestions or thoughts appreciated.
Update: Here is how I accessing the properties on the partial views.
<div class="data-group">
<%: Html.CheckBoxFor(model => model.Property1) %>
<%: Html.LabelFor(model => model.Property1) %>
</div>
Update 2: Per request...
Controller Action (ScenarioController):
public ActionResult Index(int id = 0)
{
if (id == 0)
{
SavedScenario scenario = new SavedScenario();
scenario.AnItemList1.Add(new AnItem1());
scenario.AnItemList2.Add(new AnItem2());
return View("Index", scenario);
}
else
{
SavedScenario scenario = repository.GetScenario(id);
if (scenario == null)
return View("NotFound");
else
return View("Index", scenario);
}
}
[HttpPost]
public ActionResult Index(SavedScenario scenario)
{
if (ModelState.IsValid && TryUpdateModel(scenario, "SaveScenario"))
{
repository.Add(scenario);
repository.Save();
}
return View(scenario);
}
Rendered HTML (I can only include parts of it - this is a small sample of what is in the form):
<form action="/Scenario" id="form0" method="post">
<!-- This is the one that works - the basic Scenario. Top level. -->
<fieldset>
<legend>Scenario Information</legend>
<div class="data-group">
<div class="editor-label">
<label for="ScenarioName">Scenario Name</label>
</div>
<div class="option1">
<input class="wide" id="ScenarioName" name="ScenarioName" type="text" value="" />
</div>
<div class="validation">
<div><span class="field-validation-valid" id="ScenarioName_validationMessage"></span></div>
</div>
</div>
</fieldset>
<!-- This does not work or get submitted (as far as I can tell). -->
<div id="tab2">
<fieldset>
<legend>Tab2</legend>
<div class="data-group">
<input id="Property1" name="Property1" type="checkbox" value="true" /><input name="Property1" type="hidden" value="false" />
<label for="Property1" />
</div>
</div>
</fieldset>
</form>
My apologies for having to keep this so generic.
Hard to guess from this much code. However you should make sure that all properties of your models have the same prefix when they are posted back to the server
Edit: form field names should match property names of your model to correctly bind all values. You have two fields with the same name that you can bind in following way
[HttpPost]
public ActionResult Index(SavedScenario scenario, List<bool> Property1)
{
// here you can do with values coming in property1
if (ModelState.IsValid && TryUpdateModel(scenario, "SaveScenario"))
{
repository.Add(scenario);
repository.Save();
}
return View(scenario);
}
It might be issue with naming the fields on your partial forms. Try naming the fields on your partial views by prefixing it with the name of the Model passed into it...like 'AnItemList1.name' instead of just 'name'..I am just guessing here though...but that's what I did sometimes to fix the problem when I was getting values as null..