Thymeleaf, default values does not appear in my update form - forms

I'm learning java and I'm practicing with thymeleaf. I made an little app where I have a list of persons (arraylist). I can add a person through a form but also edit a person from the list to update the person's firstname, lastname or birthdate through a form. Here is my problem I want when I edit a person to have its default values(firstname, lastname, bithdate) on the update form so that we can then change only the fields of interest. I have this code:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Update Person</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Update a Person:</h1>
<!-- some tests I made to test if the value appears in the field -->
<!-- <input type="text" name="id" th:value="${person.id}" /> -->
<!-- <input type = "text" name = "firstName" th:value = "${person.firstName}" /> -->
<!-- <input type = "text" name = "sometext" th:value = "hello world" /> -->
<form th:action="#{/updatePerson/{id}(id=${person.id})}"
th:object="${person}" method="POST">
First Name:
<input type="text" th:field="*{firstName}"/>
<br/>
Last Name:
<input type="text" th:field="*{lastName}" />
<br/>
Date of Birth (DD/MM/YYYY):
<input type="date" th:field="*{birthDate}" />
<br/>
ID:
<input type="text" th:field="*{id}" />
<br/>
<input type="submit" value="Update" />
</form>
<br/>
<!-- Check if errorMessage is not null and not empty -->
<div th:if="${errorMessage}" th:utext="${errorMessage}"
style="color:red;font-style:italic;">
...
</div>
</body>
</html>
None of my default values appears in the fields except for the id. Whether I use th:field="{id}" or name="id" th:value="${person.id}". Both synthax work but the others (ie: th:field="{firstName}" or name = "firstName" th:value = "${person.firstName}" same goes for lastname and birthdate), nothing works. I even tried th:value = "hello world" (commented in the above code), it does appear! So why my person firstname, lastname, bithdate don't appear? What is wrong? My person.list html works though:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Person List</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Person List</h1>
Add Person
<br/><br/>
<div>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date of Birth</th>
<th>Edit</th>
<th>Delete Name</th>
</tr>
<tr th:each ="person : ${list}">
<td th:utext="${person.firstName}">...</td>
<td th:utext="${person.lastName}">...</td>
<td th:text="${#temporals.format(person.birthDate,'dd-MM-yyyy')}">...</td>
<td><a th:href="#{/updatePerson/{id}(id=${person.id})}">
<span>
<img src="https://img.icons8.com/clouds/40/000000/edit.png">
</span>
</a></td>
<td>
<form th:action="#{/deletePerson}" th:method="POST">
<input type = "hidden" name = "firstName" th:value = "${person.firstName}" />
<input type = "hidden" name = "lastName" th:value = "${person.lastName}" />
<input type = "hidden" name = "id" th:value = "${person.id}" />
<input type = "hidden" name = "birthDate" th:value = "${person.birthDate}" />
<button type = "submit" >
<span>
<img src="https://img.icons8.com/metro/26/000000/delete.png" />
</span>
</button>
</form>
</td>
</tr>
</table>
</div>
<div>
<form th:action="#{/changeDao}" th:method="POST">
<select name="daoChoice">
<option th:value="none" disabled>Choisissez votre Dao</option>
<option id="jdbc" th:value="JDBC">Jdbc</option>
<option id="memory" th:value="MEMORY" th:selected="${isMemory}">Memory</option>
</select>
<button type="submit">Valider</button>
</form>
</div>
<div>
<form th:action="#{/excelLoad}" th:method="GET">
<button type="submit">Local Load</button>
</form>
</div>
<div>
<form th:action="#{/UploadFile}" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td><label>Upload and Add to the table</label></td>
<td><input type="file" th:value = "file" th:name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
</div>
<div>
<form th:action="#{/exportToExcel}" th:method="POST">
<button type="submit">Export to Excel</button>
</form>
</div>
</body>
</html>
Above my personList.html, person's firstName lastName and birthdate is printed correctly with this code:
<tr th:each ="person : ${list}">
<td th:utext="${person.firstName}">...</td>
<td th:utext="${person.lastName}">...</td>
<td th:text="${#temporals.format(person.birthDate,'dd-MM-yyyy')}">...</td>
but why in my update form this is not working ?
I'm a newbie in java programming and also in thymeleaf (also newbie), so I'd really appreciate some explanations along some tips! thanks a lot!

I found it with another post where there was a simple explanation about the key/value pair in modelAddAttribute:
You can access variables value by ${key}.
Example
model.addAttribute("key", value);
Understanding that I found my mistake in my controller:
#RequestMapping(value = { "/updatePerson/{id}" }, method = RequestMethod.GET)
public String showUpdatePersonPage(#PathVariable("id") int id, Person person, Model model) {
person = personDao.findPerson(id);
model.addAttribute("person", person);
return "updatePerson";
}
Before it was:
#RequestMapping(value = { "/updatePerson/{id}" }, method = RequestMethod.GET)
public String showUpdatePersonPage(#PathVariable("id") int id, Person person, Model model) {
person = personDao.findPerson(id);
model.addAttribute("personToModify", person);
return "updatePerson";
}
And in my html the code was:
<form th:action="#{/updatePerson/{id}(id=${person.id})}"
th:object="${person}" method="POST">
First Name:
<input type="text" th:field="*{firstName}"/>
<br/>
Last Name:
<input type="text" th:field="*{lastName}" />
<br/>
Date of Birth (DD/MM/YYYY):
<input type="date" th:field="*{birthDate}" />
<br/>
ID:
<input type="text" th:field="*{id}" />
<br/>
<input type="submit" value="Update" />
</form>
So that was because the key name used "personToModify" couldn't be found in the html as the object name used wasn't properly named:
th:object="${person}"

I can't see your Person class or controller but, for example, keeping it clean, you can create PersonForm class which can look like (might need to change Date)
import java.util.Date;
public class PersonForm {
private String firstName;
private String lastName;
private Date birthDate;
public PersonForm() {
}
public PersonForm(Person person) {
this.firstName = person.getFirstName();
this.lastName = person.getLastName();
this.birthDate = person.getBirthDate();
}
As you can see, it has fields which needs to populated and you set them in constructor, you can also apply validation annotations here if needed.
In your controller you would need to retrieve Person and using it, create and add PersonForm as model attribute. i.e.
#GetMapping("/person/edit/{id}") // you might not use id, might be username
public String editPerson(#PathVariable Long id, Model model) {
Person person = personRepository.getOne(id); // or service
PersonForm personForm = new PersonForm(person);
model.addAttribute("personForm", personForm);
// other stuff
// return html
}
and then change th:object="${person}" to th:object="${personForm}"
Now all th:field="*{firstName}" and others should be populated.

Related

Handler method not firing when called by form in Razor Pages

I've gone through dozens of articles, docs, and stack overflow questions (even the one with a similar intro)regarding the same issues but it still persists.
I've tried this with putting the functions in the .cshtml.cs page and on the .cshtml page, named and unnamed handler names, different framework for sending emails, and adding an empty action field in the form along with other fixes but the issue seems to be that the handler method itself is not firing while the form is submitting. Any and all help is appreciated and please let me know if more information is needed.
My HTML form:
<form method="POST" asp-page-handler="email">
<!-- Name input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientName" type="text" placeholder="Enter your name..." required/>
<label for="name">Full name*</label>
</div>
<!-- Email address input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientEmail" type="email" placeholder="name#example.com" required/>
<label for="email">Email address*</label>
</div>
<!-- Phone number input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientPhone" type="tel" placeholder="(123) 456-7890"/>
<label for="phone">Phone number</label>
</div>
<!-- Message input-->
<div class="form-floating mb-3">
<textarea class="form-control" name="clientMessage" type="text" placeholder="Enter your message here..." style="height: 10rem" required></textarea>
<label for="message">Message*</label>
</div>
<!-- Submit Button-->
<div class="d-grid"><button class="btn btn-primary btn-xl" type="submit" value="submit">Submit</button></div>
</form>
My functions as they are currently:
public void OnPostEmail()
{
var clientEmail = Request.Form["clientEmail"];
var clientName = Request.Form["clientName"];
var clientPhone = Request.Form["clientPhone"];
var clientMessage = Request.Form["clientMessage"];
sendEmail(clientEmail, clientName, clientPhone, clientMessage);
}
public void sendEmail(string clientEmail, string clientName, string clientPhone, string clientMessage)
{
var errorMessage = "";
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "smtp.google.com";
WebMail.SmtpPort = 587;
WebMail.UserName = "***#gmail.com";
WebMail.Password = "MYPASSWORD";
WebMail.From = "***#gmail.com";
WebMail.EnableSsl = true;
// Send email
WebMail.Send(to: clientEmail,
subject: $"Request from: + {clientName}",
body: $"{clientMessage}\nPhone: {clientPhone}\nEmail: {clientEmail}"
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
}

A Simple Grails form. I'm at a loss

I will preface this by saying my background is Graphic Design (been doing JavaScript for a few years).Ok, I've been looking and looking for a simple tutorial on how to create a basic form with a a controller, that sends the form info in the body of an email.
This is what I have in my GSP:
<g:form name="batchform" url="[action:'forminfo', controller:'onboardingform'] />
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${params.apparea01}' />
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${params.deptname02}' />
<input type="submit" value="Submit Form" id="FormButton" >
<g:form>
And the controller is where I get confused:
package .com
import util.Environment
import MailTools
import MetricsLogger
class OnboardingformController {
String apparea01,
String deptname02
static constraints = {
apparea01 blank: false, nullable: false
deptname02 blank: false, nullable: false
}
def index() {
render (view:'onboardingform.gsp')
}
sendMail {
to 'me#email.com'
cc params.mail
subject 'I am the form test in the subjectline'
body 'i am the body of the form. I should have vars here that display the user input from form fields'
}
}
I do not currently have a DOMAIN set up since there is no DB attached to this site. I just need to shove those Field Inputs into the Email body. I realize this maybe a very basic operation that escapes me (my background is Fine Arts, not Computer Science).
The MailTools is configured already to a default mailbox. The form needs to be send to another email address.
The MetricsLogger captures user info upon landing on the page.
Thanks in advance. This knowledge will open my eyes in my quest to be an Artist / Programmer :)
Ok, I came up with this controller in
grails-app/controllers/test/OnboardingformController.groovy:
package test
class OnboardingformController {
def index() {
render( view: 'onboardingForm.gsp' )
}
def formSubmission( String apparea01, String deptname02, String email ) {
println "Send Mail from $email to me#email.com with apparea01=$apparea01 and deptname02=$deptname02"
/*
// Commented out for now so I don't have to set up mail ;-)
sendMail {
to 'me#email.com'
cc params.mail
subject 'I am the form test in the subjectline'
body 'i am the body of the form. I should have vars here that display the user input from form fields'
}
*/
redirect( action:'index' )
}
}
And this GSP grails-app/onboardingform/onboardingform.gsp:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Onboarding</title>
</head>
<body>
<g:form action="formSubmission">
<p>
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${params.apparea01}' />
</p>
<p>
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${params.deptname02}' />
</p>
<p>
<label>Email</label>
<g:textField name="email" type="text" placeholder="Place Holder Text Field 3" value='${params.email}' />
</p>
<p>
<input type="submit" value="Submit Form" id="FormButton" >
</p>
</g:form>
</body>
</html>
Which when the form is filled in, should print out the values you entered (to the console) and redirect to the form. Let me know if anything doesn't make sense :-)
If you need validation (without a domain object), you can use a Command Object. This changes the controller to:
package test
class OnboardingformController {
def index() {
render( view: 'onboardingForm.gsp' )
}
def formSubmission( SubmissionCommandObject cmd ) {
if( !cmd.validate() ) {
render( view: 'onboardingForm.gsp', model:[ data: cmd ] )
return
}
else {
println "Send Mail from $cmd.email to me#email.com with apparea01=$cmd.apparea01 and deptname02=$cmd.deptname02"
}
redirect( action:'index' )
}
}
class SubmissionCommandObject {
String apparea01
String deptname02
String email
static constraints = {
apparea01 blank: false, nullable: false
deptname02 blank: false, nullable: false
email blank: false, email: true
}
}
And the view to:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Onboarding</title>
</head>
<body>
<g:hasErrors bean="${data}">
<g:renderErrors bean="${data}" as="list" />
</g:hasErrors>
<g:form action="formSubmission">
<fieldset>
<p class="prop ${hasErrors(bean:data, field:'apparea01', 'errors')}">
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${data?.apparea01}' />
</p>
<p class="prop ${hasErrors(bean:data, field:'deptname02', 'errors')}">
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${data?.deptname02}' />
</p>
<p class="prop ${hasErrors(bean:data, field:'email', 'errors')}">
<label>Email</label>
<g:textField name="email" type="text" placeholder="Place Holder Text Field 3" value='${data?.email}' />
</p>
<p>
<input type="submit" value="Submit Form" id="FormButton" >
</p>
</fieldset>
</g:form>
</body>
</html>
Obviously, this could be prettier, but will suffice for this quick example

calling a rest service on submission of form

I have a form which has some values. When i submit the form i want the current logged in user's userid to be passed in the path to call a rest service handler in my controller. I don't know what to write in the form action to make it happen.
my controller handler
#RequestMapping(value="/redemptionRedirect1/{userId}", method=RequestMethod.GET)
public #ResponseBody Transaction submitRedemption(#PathVariable("userId") long userId ,#ModelAttribute("redemption") Transaction transaction)
{
boolean flag;
Authentication auth =SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
User user=userService.getUser(name);
transaction.setUser(user);
flag = transactionService.addRedemptionTransactions(transaction);
return transaction;
}
>
my jsp
<body>
<form id="account" action="redemptionRedirect1/${user.userId}" method="get">
<table>
<tr><td>Amount: </td><td><input type="text" maxlength="5" value='<c:out value="${amount}"/>' readonly="readonly"/></td></tr>
<tr><td>
Bank Accounts: </td><td><select id="bankaccounts">
<c:forEach items="${baccounts}" var="account">
<option value='<c:out value="${account.accountNumber}"/>'>
<c:out value="${account.name}"/>
</option>
</c:forEach>
</select>
</td></tr>
<tr><td>Demat Account: </td><td><input type="text" placeholder='<c:out value="${daccount.dematName}"/>' value='<c:out value="${daccount.dematAccountNumber}"/>' readonly="readonly"/></td></tr>
<tr><td><input type="submit" value="Confirm"/></td></tr>
</table>
<div style="visibility: hidden;"><input id="user" type="text" value='<c:out value="${user.userId}"/>'/></div>
<div id="personFormResponse"></div>
</form>
</body>

Unable to return to the desired URL or view of the JSP

<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery.validate.min.js"></script>
<script>
function setHiddenVal(){
var goAhead = true;
var myVal="I am hidden value";
document.getElementById("secretValue").value = myVal;
if (goAhead == true) {
document.forms["register-form"].submit();
}
}
</script>
</head>
<body>
<!--Main Container Starts here-->
<div class="main_container">
<div class="header">
<div class="right_panel">
<h2 align="center"><u>User Master</u></h2>
<div class="top-form">
<div>
**<form:form action="/usermaster" modelAttribute="CustomerForm" id="register-form" method="POST">**
<table cellspacing="0" cellpadding="0" border="" class="form1">
<tr>
<td class="label">Name:</td>
<td>
<form:input path="firstname"/>
</td>
</tr>
<tr>
<td class="label">Password:</td>
<td>
<form:input path="password"/>
</td>
</tr>
</tbody>
</table>
<div>
<table>
<tr>
<td> </td>
<td>
<input type="button" class="btn blue px16" value="Search" />
<input type="button" name="submit" id="btnsubmit" value="Submit" onclick="setHiddenVal();"/>
<input type="button" class="btn blue px16" value="Clear" />
<input type="button" class="btn blue px16" value="Change Password" />
<input type="button" class="btn blue px16" value="Manage User Notification Profile" />
</td>
</tr>
</table>
</div>
</form:form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</body>
</html>
so above one is my code for jsp and below is the code of controller
#RequestMapping(value={"/usermaster" }, method = RequestMethod.POST)
public final String addUserMaster(#ModelAttribute("CustomerForm") CustomerForm pricing, Map<String, Object> map,
Model model, HttpServletRequest request) {
System.out.println("the first name is "+pricing.getFirstname());
System.out.println("the password is "+pricing.getPassword());
return "usermaster";
}
#RequestMapping(value={"/showusermaster" }, method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
But my page gets open up using a popup with the url:
C:\Users\ganganshu.s\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\YW6383E8\usermaster
so it should open like
http://localhost:8080/enbee/usermaster
Could you please tell me what should I put in the form action.. as I think some mistake is there in the form action does in spring MVC we put the action like in the case I mentioned above.
Spring confg file is given below :
<mvc:interceptors>
<bean class="com.enbee.admin.interceptor.AuthenticationInterceptor" />
<!-- Declare a view resolver-->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1" />
and the jsp name is usermaster.jsp
and in the sidemenu.jsp I have changed to this :
<li>User Master</li>
Change the method parameter of RequestMapping annotation to RequestMethod.POST:
#RequestMapping(value="/usermaster", method = RequestMethod.POST)
public final String addUserMaster(...){
...
}
so that when you submit your form to the URL /usermaster using method="POST" this method will get executed.
You also need to have a method (mapped to an URL) that will show this page to the user. You can use a method as below for this:
#RequestMapping(value = "/showusermaster", method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
With this method in place, the URL
http://localhost:8080/enbee/showusermaster
will show the usermaster.jsp page to the user. Now when you submit this form, the above addUserMaster method will be invoked.
You don't have to create new jsp file. The url /showusermaster will return the usermaster.jsp to the user, where the user can add form values and submit the form:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
<c:url var="submitUrl" value="/usermaster">
<form:form id="form" action="${submitUrl}" modelAttribute="CustomerForm" method="POST">
Now when the user clicks on the submit button, this form will be submitted to /usermaster URL and will be handled by addUserMaster method.
Try to specify the content type returned by your controller method, adding produces = "text/html" param to your #RequestMapping annotation.

jQuery Datepicker only firing if I first click on another input field

I'm having some strange behaviour when using the datepicker. When I load the page, and directly click on the datepicker input, nothing happens. When I click again, nothing happens. But when I click on another input field and then try again the datepicker field, it'll show up.
The issue showed up, after I put the datepicker trigger into a live function, because I have input which will be dynamically generated.
This is my code:
$(".date").on('click', function() {
$(this).datepicker({
dateFormat: "dd.mm.yy",
altField: $(this).closest("td").find(".dateFormated"),
altFormat: "yy-mm-dd"
})
})
Edit: I have seen that live() is deprecated as of 1.7. I therefore switched live() for on(). Didn't solve the issue though.
Whole Html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
<link rel="stylesheet" href="http://localhost:8082/ivy/page/designer/ZWM$1/css/cupertino/jquery-ui-1.9.2.custom.css" />
<script type="text/javascript" src="http://localhost:8082/ivy/page/designer/ZWM$1/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:8082/ivy/page/designer/ZWM$1/js/jquery-ui-1.9.2.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
counter = 0;
$("#addRow").click(function() {
counter++;
rowHtml = '\
<tr class="datarow" id="row' + counter + '">\
<td><input type="text" class="date" /><input type="text" class="dateFormated" /></td>\
<td><input type="text" class="from" /></td>\
<td><input type="text" class="to" /></td>\
<td>\
<select class="type">\
<option value="1">Typ 1</option>\
<option value="2">Typ 2</option>\
</select>\
</td>\
<td class="removeRow" id=' + counter + '>X</td>\
</tr>';
$('#submitButton').before(rowHtml);
})
$(".removeRow").live("click", function() {
id = $(this).attr("id");
$("#row" + id).remove();
})
$("[name=formZeitdaten]").submit(function(i) {
values = "";
$(".datarow").each(function(j) {
tr = $(this);
date = tr.find('td').find('.date').val();
from = tr.find('td').find('.from').val();
to = tr.find('td').find('.to').val();
type = tr.find('td').find('.type').val();
values = values + date + ',' + from + ',' + to + ',' + type + ';';
})
console.log(values);
$("[name=dataset]").val(values);
})
$("#slider").slider({
range: true,
min: 0,
max: 1440,
step: 15,
values: [30, 210],
slide: function(event, ui) {
$(".date").val(ui.values[0] + ":" + ui.values[1]);
}
});
$(".date").on('click', function() {
$(this).datepicker({
dateFormat: "dd.mm.yy",
altField: $(this).closest("td").find(".dateFormated"),
altFormat: "yy-mm-dd"
})
})
});
</script>
</head>
<body>
<span id="test"></span>
<form name="formZeitdaten" method="post">
<table id="zeitdaten">
<tr>
<td>Datum</td>
<td>Von</td>
<td>Bis</td>
<td>Typ</td>
<td id="addRow"><input type="button" value="Hinzufügen" /></td>
</tr>
<tr class="datarow">
<td><input type="text" class="date" /><input type="text" class="dateFormated" /></td>
<td><input type="text" class="from" /></td>
<td><input type="text" class="to" /></td>
<td>
<select class="type">
<option value="1">Typ 1</option>
<option value="2">Typ 2</option>
</select>
</td>
<td></td>
</tr>
<tr id="submitButton">
<td><input type="submit" /></td>
</tr>
</table>
</form>
<div id="slider"></div>
</body>
</html>
In your addRow function, add:
$("#row"+counter+" .date").datepicker({
dateFormat: 'dd-mm-yy',
minDate: 0,
showButtonPanel: true,
showAnim: 'show'
});
after you add the element to the DOM. You can then get rid of the $(".date").on('click',...) statement later.
This should work for you
$('.date').datepicker({
dateFormat: 'dd-mm-yy',
minDate: 0,
showButtonPanel: true,
showAnim: 'show'
});