Avoiding field prepopulation in a thymeleaf form with Spring-Boot - spring-boot

I am having a trouble getting rid of the field prepopulation in a thymeleaf form and displaying text placeholders instead.
Here is the snippet of the form:
<form action="#" th:action="#{/catch/save}" th:object="${catch}" method="post">
<input type="hidden" th:field="*{id}">
<input type="text" th:field="*{species}" th:placeholder="Species"
class="form-control mb-4 col-3">
<input type="text" th:field="*{length}" th:placeholder="Length"
class="form-control mb-4 col-3">
<input type="text" th:field="*{weigth}" th:placeholder="Weigth"
class="form-control mb-4 col-3">
and here is the image of the resulting form:
Prepopulated form
My goal is to have the two fields prepopulated with "Length" and "Weigth". These fields correspond to int and double object fields, so if I understand correctly they are initiated with 0 when the bean is created and therefore so are th:fields when the form is loaded.
Could you help me find a way to solve this?
Thank you in advance

Related

Thymeleaf populate a date field with date

I need help populating a date field for an edit page in Thymeleaf. So Im a beginner with this but I've tried so many variations I don't know the best approach now. So Im passing the Employee list to thymeleaf with a model.addTribute("employee", employee) and the data looks like this:
Employee: Employee{id=2, name='John Smith', contractedFrom='2022-01-01', contractedTo='2022-12-31', employeeProjects=[EmployeeProject{id=1, project=Project{id=1, projectNumber=61741501, name='Project 1', startDate='2022-04-01', endDate='2022-09-30', projectLengthInMonths=3.0, currentBookedMonths=0.0, remainingBookedMonths=0.0, numberOfEmployees=0}, employeeBookedMonths=4.0, employeeProjectStartDate=2022-05-01, employeeProjectEndDate=2022-09-15, projectName='null'}, EmployeeProject{id=2, project=Project{id=2, projectNumber=61241514, name='Project 2', startDate='2022-01-01', endDate='2023-03-31', projectLengthInMonths=24.0, currentBookedMonths=0.0, remainingBookedMonths=0.0, numberOfEmployees=0}, employeeBookedMonths=4.5, employeeProjectStartDate=2022-10-01, employeeProjectEndDate=2022-12-31, projectName='null'}], projectIds=[4, 5, 7, 8], startDates=[2022-01-01, 2022-05-01, 2022-10-01, 2022-08-01], endDates=null}
So the input form has the Employee name, contractedFrom and ContractedTo which work fine, then below there is a checkbox with a date field. I can populate the checkbox using the projectsIds field, but how can I populate the dates fields with the startDates array? Or is there a better way? I've also tried creating a projectDto but I couldn't get that to work either. Here is what the dto looks like:
[ProjectDto(id=1, employeeProjectStartDate=2022-01-01, employeeProjectEndDate=2022-04-30), ProjectDto(id=2, employeeProjectStartDate=2022-05-01, employeeProjectEndDate=2022-09-15), ProjectDto(id=3, employeeProjectStartDate=2022-10-01, employeeProjectEndDate=2022-12-31), ProjectDto(id=4, employeeProjectStartDate=null, employeeProjectEndDate=null)]
Any help is greatly appreciated. Here is the form code:
<form action="#" th:action="#{/ines/updateEmployee/{id}(id=${employee.id})}" th:object="${employee}"
method="POST">
<input type="hidden" th:field="*{id}" />
<input type="text" th:field="*{name}"
placeholder="Employee Name" class="form-control mb-4 col-4">
<input type="date" th:field="*{contractedFrom}"
placeholder="Contracted From" class="form-control mb-4 col-4">
<input type="date" th:field="*{contractedTo}"
placeholder="Contracted To" class="form-control mb-4 col-4">
<div th:each="proj : ${projects}">
<div class="form-group blu-margin">
<input type="checkbox" th:field="*{projectIds}" th:name="projectId"
th:text="${proj.name}" th:value="${proj.id}">
<input type="date"
th:field="*{startDates}"
class="form-control mb-4 col-4">
<!-- <input type="date"-->
<!-- th:field="*{endDates}"-->
<!-- class="form-control mb-4 col-4">-->
</div>
</div>
<button type="submit" class="btn btn-info col-2">Save Employee</button>
</form>
Image of the page, as I said the contractedFrom/To populated but not the project startDate.
You can use indices to access individual dates in the startDates array (assuming your startDates is an array of Date (i.e. Date[] startDates).
<div th:each="proj, stats : ${projects}">
<div class="form-group blu-margin">
<input type="checkbox" th:field="*{projectIds}" th:name="projectId"
th:text="${proj.name}" th:value="${proj.id}">
<input type="date"
th:value="${startDates[stats.index]}"
class="form-control mb-4 col-4">
<!-- <input type="date"-->
<!-- th:value="${endDates[stats.index]}"-->
<!-- class="form-control mb-4 col-4">-->
</div>
Or alternatively, since your ProjectDTO already contains employeeProjectStartDate and employeeProjectEndDate fields, you can access those fields in the th:each loop by using ${proj.employeeProjectStartDate} and ${proj.employeeProjectEndDate} respectively.

Spring accepting data from form getting 404 error

I am trying to take an input from a form made in a jsp called "start.jsp".
<body>
<form action=/addResults"method="post" modelAttribute="results" required="true">
<label for="email">Email Address:</label><br>
<input type="text" id="email" name="email" maxlength="50"required><br>
<label for="fullname">Full Name:</label><br>
<input type="text" id="fullname" name="fullname" maxlength="100"required>
<label for="age">Age (0-120):</label><br>
<input type="text" id="age" name="age" min="0" max="120"required>
<label for="gender">Gender:</label><br>
<input type="text" id="gender" name="gender" maxlength="45"required>
<input type="submit" value="Submit">
</form>
</p>
</body>
I'm then using code in my Controller to add this to a Class. Below is my controller code.
#RequestMapping("/addResults")
public String newHotel(Model model) {
model.addAttribute("results", new TestResults());
return "start";
}
But when I execute my Spring project it gives me an error of 404-not found. I've tried checking and rechecking my links and I can't understand how the links can't find the other pages etc. Any help would very great as I'm quite new to spring and the franework. Fred

thymeleaf 3 form action URL with parameters and get method not working

I am using Thymeleaf 3 in Spring Boot 2 web app. Below is the form code:
<form data-th-action="#{/props/r(pg=3)}" method="get">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="pt" id="p1" value="pr">
<label class="form-check-label" for="p1">P1</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="pt" id="p2" value="pr2">
<label class="form-check-label" for="p2">P2</label>
</div>
<button type="submit" class=" mb-4">Search</button>
</form>
Unfortunately when I used method get for the form, it does not append ?pg=3 in the submitted URL, the URL looks like /props/r? if no checkbox is selected. If checkbox is selected the URL looks like /props/r?pt=p1
the pg=3 part is missing.
How to fix this problem?
The problem is that you have an action #{/props/r(pg=3)} -- which translates to /props/r?pg=3 and your form is also method get. If you have parameters in both the action and the body of the form (and usemethod="get"), browsers will not combine them. Instead, the parameters of the action are removed and replaced with the paramters in the body of the form.
This is why ?pg=3 is removed and replaced with the checkbox parameters. Either use post instead, or include pg as a hidden form element.
Instead of putting pg as parameter at the form url, consider putting it inside a hidden field like below.
<input type="hidden" name="pg" value="3">

Firefox bug with input type password?

I have a problem in an application I'm developing, if I have input fields with type 'password' then another input field is populated with data from a completely different element.
If I set the type of the element that is 'password' to 'text' there is no problem.
Unforunatley I can't post an example of jsFiddle, but I've searched around and found other people having a problem with Firefox with an older version.
I'm using version: 43.0b9 with Firebug 2.0.13
IE, Chrome and Safari do not do this with the exact same page loaded, but its very repeatable and very realiable in FireFox.
I've set the attribute autocomplete="off" but no difference.
This problem has me scratching my head...I've commented out just about everything, but the problem still occurs, some how my name and login password are finding there way into two INPUT elements, the same page in Chrome, IE and Safari does not do this.
I was having the same problem, and finally solved it after reading this answer to other similar question: https://stackoverflow.com/a/10745884/6938721
In my case, I had a lot of input fields divided into multiple fieldsets, and sent them through AJAX.
Well, the solution was to surround each <fieldset>...</fieldset> with <form>...</form> labels.
Originally I had something like:
<fieldset>
<input type="text" name="field1">
<input type="password" name="field2">
<input type="password" name="field3">
</fieldset>
<fieldset>
<input type="text" name="field4">
<input type="password" name="field5">
<input type="password" name="field6">
</fieldset>
And after applying the solution I get:
<form>
<fieldset>
<input type="text" name="field1">
<input type="password" name="field2">
<input type="password" name="field3">
</fieldset>
</form>
<form>
<fieldset>
<input type="text" name="field4">
<input type="password" name="field5">
<input type="password" name="field6">
</fieldset>
</form>
Edit:
The key is to not have more than 3 password inputs inside a <form> block. The document works as a <form> block by itself
Hope this helps

Honeypot protection with Ajax

Recently i got attacked by nasty auto-form fill bots which filled my shout form with all sorts of spam. My shout form consist from a html file with 2 textboxes,an ajax script(for refreshing without reloading) and my php file for handling all the inserting data into my DB.
I am thinking implementing a hidden textbox for a minimum protection against these bots but with no luck since i cant pass the honeypot data to my php file. My code:
HTML Form
<form class="form" method="post" action="postdata.php">
<fieldset id="inputs">
<input id="name" name="name" type="text" placeholder="name" maxlength="20">
<textarea id="message" name="message" type="text" placeholder="message" maxlength="255"></textarea>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Submit">
</fieldset>
</form>
Ajax script
$(function(){refresh_shoutbox();$("#submit").click(function(){var a=$("#name").val();var b=$("#message").val();var c="name="+a+"&message="+b;$.ajax({type:"POST",url:"postdata.php",data:c,success:function(d){$("#shout").html(d);$("#message").val("");$("#name").val("")}});return false})});
function refresh_shoutbox(){var a="refresh=1";$.ajax({type:"POST",headers:{"cache-control":"no-cache"},url:"postdata.php",data:a,success:function(b){$("#shout").html(b)}})};
postdata.php file
<?php
if($_POST['name'] or $_POST['message']) {
$name= $_POST['name'];
$message= $_POST['message'];
///do other stuff/////
?>
I will insert a hidden field in my html form
<input id="email" name="emails" style="display:none"></br>
but i cant manage to pass the extra value to my existing ajax script.Tried some code but with no luck.
Any help so i can get my shoutbox up and running again?

Resources