Thymeleaf input type="date" can not display and update - spring-boot

I can't find the right way to display the "birthday" field from datbase!
Even when i try to submit the new value to db, it doesn't work. What i'm doing wrong?
Here is my code:
Controller
#RequestMapping(value = {"/settings"}, method = RequestMethod.GET)
public ModelAndView settings() {
ModelAndView model = new ModelAndView();
model.addObject("user", user);
model.addObject("countries", getListOfCountries());
model.setViewName("user/settings");
return model;
}
#RequestMapping(value = {"/settings"}, method = RequestMethod.POST)
public ModelAndView updateUserGeneralSettings(#ModelAttribute User user) {
ModelAndView model = new ModelAndView();
userService.update(user);
model.addObject("user", user);
model.addObject("countries", getListOfCountries());
model.setViewName("user/settings");
return model;
}
HTML
<form method="POST" th:action="#{/settings}" th:object="${user}">
<div>
</div>
...
...
<div class="costum-field">
<label for="dateOfBirth" th:text="#{field.dateOfBirth}"></label>
<input type="date" id="dateOfBirth" class="form-control" th:field="*{dateOfBirth}"/>
</div>
...
...
<div>
</div>
</form
View in browser
So, as you can see all fields are working properly. Please suggest what is my mistake.

Related

check if Team exists in the database or the input field is empty

It is necessary to check if the input fields for Team are empty, and whether there is such a Team in the repository.
If the field is not empty and there is no such Team, then you can create a new Team. If the field is empty or Team already exists, then give an error
AdminController
#Controller
public class AdminController {
#RequestMapping(value = "/admin/team", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String addTeam(Model model, #ModelAttribute("teamForm") #Validated TeamForm teamForm,
BindingResult result, final RedirectAttributes redirectAttributes) {
System.out.println("addTeam invoked");
if (result.hasErrors()) {
return "/admin";
}
Team newTeam = new Team();
newTeam.setName(teamForm.getName());
newTeam.setUrl(teamForm.getUrl());
teamRepository.save(newTeam);
return "teamList";
}
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
model.addAttribute("teamForm",new TeamForm());
model.addAttribute("eventForm",new EventForm());
model.addAttribute("usersForm",new UsersForm());
return "admin";
}
admin.html
<form th:action="#{/admin/team}"
th:object="${teamForm}" method="POST">
Team name:
<input type="text" th:field="*{name}" />
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect Name</p>
<br/>
Url :
<input type="text" th:field="*{url}" />
<br/>
<input type="submit" value="Create Team" />
</form>

Spring not reading model attributes from form submission

In my current spring-boot project, I have this form:
<form class="form-container" id="form" method="post" th:object="${command}" th:action="#{/usuario/register}">
...
<div class="form-row">
<div class="col-25">
<label for="login">Login</label>
</div>
<div class="col-75">
<input type="text" id="login" th:field="*{username}" placeholder="Login">
</div>
</div>
...
</form>
which is handled by this spring controller:
#RequestMapping(value = "/register", method=RequestMethod.POST)
#ResponseBody
public void doRegister(#Valid Usuario object, BindingResult result) throws Exception {
this.serv.register(object);
}
my problem is that object is getting a null value, not allowing the program to persist the data. Displaying the content for both variables object and result, they show null; but if I try display the parameter's value with:
System.out.println("result.model.username: "+result.getModel().get("username"));
the correct value is shown. What's the issue here, why #Valid Usuario object, BindingResult result get me a null value, but HttpServletRequest gets the correct values?
UPDATE
Based on the sugestion below, I try this:
#ModelAttribute(value = "usuario")
public Usuario newEntity()
{
return new Usuario();
}
#RequestMapping(value = "/register", method=RequestMethod.GET)
public String formRegister(Model model) {
model.addAttribute("command", newEntity());
return "register";
}
#RequestMapping(value = "/register", method=RequestMethod.POST)
#ResponseBody
public void doRegister(#ModelAttribute("usuario") Usuario object) throws Exception {
this.serv.register(object);
}
But got the same problem.
I managed to solve this issue changing the parameter:
#ModelAttribute("usuario") Usuario object
to:
#ModelAttribute("command") Usuario object
following the suggestion in the comment above (from M.Deinum)

Thymeleaf form - how to pass a value for model attribute from one controller method to another one

I'm struggling with adding products into product table for a specific user, whiich is logged via log method. The issue is that the attribue userLogin loses his value and is not equal to the user who logged into. So the actual value for attribute userLogin in addProduct method is null, hence there is an exception.
#RequestMapping("/home")
public String home(Model model) {
model.addAttribute("customer", new Customer());
model.addAttribute("userLogin", new Customer());
return "register";
}
#PostMapping("/save")
public String save(#ModelAttribute(value = "customer") #Valid Customer customer, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new NotValidInputException();
}
if (customerService.checkIfCustomerIsInDb(customer)) {
throw new CustomerAlreadyExists();
}
customerService.saveCustomerIntoDb(customer);
return "saved";
}
#ExceptionHandler(NotValidInputException.class)
public String notValidInputExceptionHandler() {
return "databaseError";
}
#ExceptionHandler(CustomerAlreadyExists.class)
public String customerAlreadyInDbHandler() {
return "customerError";
}
#RequestMapping("/log")
public String login(Model model, #ModelAttribute(name = "userLogin") Customer customerFromLoginForm) {
if (Objects.isNull(customerService.getUserByLoggingDetails(customerFromLoginForm))) {
return "userNotFound";
}
model.addAttribute("product", new Product());
return "logged";
}
#PostMapping(value = "/addProduct")
public String addProduct(#ModelAttribute("userLogin") Customer customerFromLoginForm, #ModelAttribute(value = "product") Product product) {
// customer is null
customerFromLoginForm = customerService.findCustomerById(customerFromLoginForm.getId());
product.setCustomer(customerFromLoginForm);
customerFromLoginForm.setProducts(Arrays.asList(product));
productService.addProduct(product);
return "logged";
}
The form in logged. html
<form th:method="post" th:action="#{addProduct}" th:object="${product}">
<input type ="text" th:field="*{name}" placeholder="Name" /><br />
<input type ="text" th:field="*{category}" placeholder="Category" /><br />
<input type="number" th:field="*{price}" placeholder="Price" /><br />
<input style="text-align: center" type="submit" value="Add Product" /> </form>
Not sure what I'm missing here
See this answer: Not able to pass model Attribute passed from controller to thymeleaf html back to another controller .
In general, I would use a hidden input for it, e.g:
<input type ="hidden" th:name="userLogin" th:value="${userLogin}" />
Then your controller method should get it. Let me know if this helps.

#requestmapping and ModelAndView

Hi help me please with Spring RequestMapping. I have page like this:
<form action="/add_photo" enctype="multipart/form-data" method="POST">
Photo: <input type="file" name="photo">
<input type="submit" />
</form>
and controller like this:
#Controller
#RequestMapping("/")
public class MyController {
private Map<Long, byte[]> photos = new HashMap<>();
#RequestMapping("/")
public String onIndex() {
return "index";
}
#RequestMapping(value = "/add_photo", method = RequestMethod.POST)
public ModelAndView onAddPhoto(#RequestParam MultipartFile photo) {
if (photo.isEmpty()) {
throw new PhotoErrorException();
}
try {
long id = System.currentTimeMillis();
photos.put(id, photo.getBytes());
ModelAndView model = new ModelAndView();
model.addObject("photo_id", id);
model.setViewName("result");
return model;
} catch (IOException e) {
throw new PhotoErrorException();
}
}
}
method "onIndex" is working but onAddPhoto seems not and when I click button whith URL "/add_photo" it gives me 404 instead page "result"
Use pageContext in your jsp page as:
<form action="${pageContext.request.contextPath}/add_photo" enctype="multipart/form-data" method="POST">
Photo: <input type="file" name="photo">
<input type="submit" />
</form>
For more details: Check this

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

Resources