in GET method I'm adding these to the model:
model.addAttribute("team", team);
model.addAttribute("players", team.getPlayers());
model.addAttribute("inviting", new InvitingPlayerToTeam());
And a fragment of view with this model:
<div id="news" th:fragment="playerList">
<span>Nazwa: </span>
<span th:text="${team.name}">nazwa teamu</span>
<br>
<span th:each="player : ${players}" th:utext="${player.username} + '</br>'">-</span>
<br><br>
<form method="POST" th:action="#{/team/invitePlayer}" th:object="${inviting}">
Nazwa <input type="text" th:field="*{username}">
<input type="hidden" th:field="*{teamId}" th:value="${team.id}">
<br>
<input type="submit" value="ZaproĊ">
</form>
</div>
What is wrong? In post method field inviting.username has good value, but inviting.teamId is 0. Where is the problem?
Just remove th:value="${team.id}". You do not need to set this value again.
You should set up your form backing bean with the correct values in your controller.
inviting.setTeamId(...)
Related
I'm writing code for currency exchanger in spring boot (I'm a begginer) and right now I'm stuck on thymeleaf template. Right now my template looks like this :
<div align="center">
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
</form>
</div>
So this means that I have one "box" where user types in number and now I want to have a second "box" where currency will be exchanged and automatically shown in that "box", How do I do that ?
EDIT : My template now looks like this (exchange.html):
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
<br/>
<br/>
<input type = "number" th:field="*{resultNumber}" disabled/>
</form>
My controller class :
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "redirect:/exchange";
}
The problem is that thymleaf can't read the modelattribute , I need to take "resultNumber" and make it visible in form tag
In your controller try this.
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "exchange";//your html page
}
and in your html page
<input type = "number" th:value="${resultNumber}" disabled/>
let me know if it works for you.
My input field
My question is how can i get all values from Name="phone" fields
JS
<script>
$(function(){
$(document.body).on('click', '.changeType' ,function(){
$(this).closest('.phone-input').find('.type-text').text($(this).text());
$(this).closest('.phone-input').find('.type-input').val($(this).data('type-value'));
});
$(document.body).on('click', '.btn-remove-phone' ,function(){
$(this).closest('.phone-input').remove();
});
$('.btn-add-phone').click(function(){
var index = $('.phone-input').length + 1;
$('.phone-list').append(''+
'<div class="input-group phone-input">'+
'<input type="number" name="phone" class="form-control" placeholder="(999) 999 9999" />'+
'<span class="input-group-btn">'+
'<button class="btn btn-danger btn-remove-phone" type="button"><span class="glyphicon glyphicon-remove"></span></button>'+
'</span>'+
'</div>'
);
});
});</script>
HTML
<div class="col-sm-10">
<div class="phone-list">
<div class="input-group phone-input">
<span class="input-group-btn">
</span>
<input type="number" name="phone" class="form-control" placeholder="(999) 999 9999" required=""/>
</div>
</div>
<button type="button" class="btn btn-success btn-sm btn-block btn-add-phone"><span class="glyphicon glyphicon-plus"></span> Add Phone</button>
</div>
Controller
#PostMapping("/applicant")
public String saveApplicantToDb(
#Valid #ModelAttribute Applicant applicant,
#RequestParam("phone") int[] phone
) {
if (phone!= null)
System.out.println(phone.length);
_applicantRepository.save(applicant);
return "applicant";
}
You are using multiple input number fields with the same name "phone" which is right, no problem with this and it should reflect back in the input #Param("phone"), but you have to make sure that the phone inputs must be of type integer for example your placeholder is totally incorrect (999) 999 9999. also the new added phone is not an integer. So make sure they are integers
The problem was name should match with your model attribute
However i was expecting int[] type of array from view but it was sending me String[] type of array problem solved and also make sure your JS code populating your input fields correctly [especially name='field_name'] should match to the attribute of your model. Check your it on browser -> inspect and collapse divs and see input field name
I am trying to check if a field in the database is true or false using the SpEl "th:if="${certs.flag == 'TRUE'}" ". If it is set to "true" the form should not be displayed. I have searched all over but can not seem to find any article that has an example of what i need exactly. Everyone seems to be using iteration. But iteration is not applicable to what i am doing.
#RequestMapping(value = "/cert_prog", method = RequestMethod.GET)
public String examsList(Model model, CertificateProgramme certificateProgramme){
Iterable<Exams> exams = examService.findAll();
Iterable<School> schools = schoolService.findAll();
Iterable<CertificateProgramme> certificateProgrammes = certificateService.findAll();
Iterable<Picture> pictures = pictureService.findAll();
CertificateProgramme mycert = certificateService.flagger(certificateProgramme);
model.addAttribute("mycert", mycert);
model.addAttribute("exams", exams);
if(!model.containsAttribute("newExam")){
model.addAttribute("newExam", new Exams());
}
model.addAttribute("certificateProgrammes", certificateProgrammes);
if(!model.containsAttribute("certificate")){
model.addAttribute("certificate",new CertificateProgramme());
}
model.addAttribute("grades", Grade.values());
model.addAttribute("regions", Region.values());
model.addAttribute("schools",schools);
if(!model.containsAttribute("newSchool")){
model.addAttribute("newSchool",new School());
}
model.addAttribute("picture", new Picture());
return "cert_prog";
}
<form th:if="${certs.flag == 'TRUE'}" method="post" th:object="${certificate}" th:action="#{/basic}" class="form-inline inline new-item">
<div th:replace="common/layout :: flash"></div>
<fieldset>
<legend> Personal Information</legend>
<div class="row" th:classappend="${#fields.hasErrors('fullName')}? 'error' : ''" >
<input type="text" class="form-control input-sm" th:field="*{fullName}" placeholder="Full Name example Jane Doe"/>
<div class="error-message" th:if="${#fields.hasErrors('fullName')}" th:errors="*{fullName}"></div>
</div>
<div class="row" th:classappend="${#fields.hasErrors('date')}? 'error' : ''" >
<input type="date" class="form-control input-sm datepicker" th:field="*{date}"
placeholder="Date Of Birth"/>
<div class="error-message" th:if="${#fields.hasErrors('gender')}" th:errors="*{date}"></div>
</div>
<div class="row" th:classappend="${#fields.hasErrors('Nationality')}? 'error' : ''" >
<input type="text" class="form-control input-sm autocomplete" th:field="*{Nationality}"
placeholder="Nationality"/>
<div class="error-message" th:if="${#fields.hasErrors('Nationality')}" th:errors="*{Nationality}"></div>
</div>
<div class="row" th:classappend="${#fields.hasErrors('email')}? 'error' : ''" >
<input type="text" class="form-control input-sm" th:field="*{email}"
placeholder="Email example jane.doe#example.com"/>
<div class="error-message" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></div>
</div>
<div class="row" th:classappend="${#fields.hasErrors('married')}? 'error' : ''" >
<select th:field="*{married}" class="form-control input-lg">
<option value="">[Select Martial Status]</option>
<option value="Single">Single</option>
<option value="Married">Married</option>
</select>
<div class="error-message" th:if="${#fields.hasErrors('married')}" th:errors="*{married}"></div>
</div>
<div class="row">
<input type="text" class="form-control input-sm" th:field="*{guardianTelephoneNumber}"
placeholder="Guardian Telephone Number"/>
</div>
<div th:classappend="${#fields.hasErrors('courseOffered')}? 'error' : ''">
<input type="text" th:field="*{courseOffered}" placeholder="CourseOffered"/>
<div class="error-message" th:if="${#fields.hasErrors('courseOffered')}" th:errors="*{courseOffered}"></div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</fieldset>
</form>
Your question doesn't really make sense to me. If you want to check a single field from the database, then you can't pass a list of items. For example, in your html:
<div th:each="certs : ${certificateProgrammes}">
<form th:if="${certs.flag == 'TRUE'}">
.
.
.
</form>
</div>
It's going through the list of ${certificateProgrammes} and assigning it to ${certs} each time in the loop. If you don't want to loop, then instead of adding Iterable<CertificateProgramme> certificateProgrammes = certificateService.findAll(); to the model, just add a single object of type CertificateProgramme. Then you can do:
model.addAttribute("certs", /* however you get the specific one you want to check */);
and in the html
<!-- no iterating required, because you know which object you're talking about -->
<form th:if="${certs.flag == 'TRUE'}">
In a .jsp page I have a form (POST method):
<div class="form-group">
<div class="col-md-3">
<input type="text" list="materials" class="form-control" name="material"/>
<datalist id="materials"></datalist>
</div>
<div class="col-md-3 col-sm-3">
<input type="number" class="form-control" name="quantity" >
</div>
</div>
I delete the html5 element required from the input to see what happens if the user submit the form without filling these inputs. In my servlet, I get this:
String material = request.getParameter("material");
String quantity = request.getParameter("quantity");
System.out.println("material="+ material + "-quantity=" + quantity);
and I get:
material=-quantity=null
The fact that I receive an empty string and a null result is it because of the diferrent type in the input?
I am currently developing a web site (Part of a university assignment)
I just put some input validation, although when I redirect due to an error from validation,
For example:
var x = document.getElementById("age").checked;
var y = document.getElementById("agreement").checked;
var z = document.getElementById("sex").value;
if(x != true & y != true & z == null)
{
response.sendRedirect("Register.jsp");
}
I was looking to have some sort of error message appear above the form, to tell the user that they have created an error within the form. (For example, if they did not enter their Gender or did not agree to either of the checkboxes). Also noted, I will change the validation code slightly to be more specific to the error in which the person has made.
Form:
<h3>Register as user</h3>
<form method="POST" action="Register">
<ul>
<li>First Name: <input type="text" name ="firstName"></li>
<li>Last Name: <input type = "text" name = "lastName"></li>
<li>Email Address: <input type = "email" name = "email"></li>
<li>Gender: Male <input type ="radio" name ="sex" value="male">
Female <input type ="radio" name ="sex" value="female"></li>
<li>User Name <input type="text" name="username"></li>
<li>Password <input type="password" name="password"></li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12: <input type = "checkbox" name="age"></li>
<li>Please check this box to agree to the Terms and Conditions <input type ="checkbox" name="agreement"></li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
Thank you for any help or advice you can give me, I really appreciate it as I am rather new to web development and I want to improve and understand techniques that web developers use.
var validate = function(form) {
var errors = [];
if (!form.sex[0].checked && !form.sex[1].checked) {
errors.push('Please select a gender');
}
if (!form.agreement.checked) {
errors.push('Please agree to T&C');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
};
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" onsubmit="return validate(this);">
<ul>
<li>First Name:
<input type="text" name="firstName">
</li>
<li>Last Name:
<input type="text" name="lastName">
</li>
<li>Email Address:
<input type="email" name="email">
</li>
<li>Gender: Male
<input type="radio" name="sex" value="male">Female
<input type="radio" name="sex" value="female">
</li>
<li>User Name
<input type="text" name="username">
</li>
<li>Password
<input type="password" name="password">
</li>
<li>You must be 12 or over to register to this web site. Please check if you are over 12:
<input type="checkbox" name="age">
</li>
<li>Please check this box to agree to the Terms and Conditions
<input type="checkbox" name="agreement">
</li>
</ul>
<br/>
<input type="submit" value="Register">
</form>
I did something like this. I have an html element which is hidden by default.
It is red and take the whole width of the div I put into.
And I've a function to manage errors :
var manageError = function(message) {
$("#element").val(message); // or $("#element").html(message) I guess
$("#element").clearQueue();
$("#element")slideDown(200).delay(10000).slideUp(200);
};
Does it help ?
use jQuery to do this. since you are learning..it will be more helpful for you.
first thing I noticed there, you have used response.sendRedirect(...); in side your javascript which is a wrong approach.
And in your form, don't use un-ordered list like approach, simply use div tags.
I will give a simple example:
<h3>Register as user</h3>
<form method="POST" action="Register.jsp" id="formId">
First Name:
<input type="text" name="firstName">Last Name:
<input type="text" name="lastName">
<div id="errMsg"></div>
<input type="button" value="submit" id="submtBtn">
</form>
and in your javascript file, use it with jQuery:
< !DOCTYPE html >
< html >
< head >
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > < /script>
</head >
< script >
$("submtBtn").click(function({
var errorMsg = "";
if ($("firstName").val === '' || $("lastName").val === '') {
errorMsg = "<b>firstName and LastName can not be empty!<b>";
$("errMsg").html(errMsg);
return;
}
$("#formId").submit();
});
< /script>
you can follow above approach.... if you're using Servlets, you could follow jQuery Ajax to submit your values. try and see...hope it will give you an idea..!
First put the validation code in a function and call that function.
function validate(){
..........write your validation code
}
Call this from submit button via onclick or onchange or onblur attribute of input tag.
You can always use HTML 5. With the required action. They can never leave anything blank if this is in. Be aware that it might work with a space in it or something.
Try this:
<li>First Name: <input type="text" name ="firstName" required></li>