Receive a Localdatetime from an html form

Asked

Viewed 108 times

0

Problem :

I am trying to receive a Localdatetime of this input within a @Controller using a <form> using the Thymeleaf.

<input class="form-control" id="dueDate" type="datetime-local" th:field="*{dueDate}"/>

But always returns null, the other fields are working perfectly.

Object used to transfer data :

public class TaskDTO {
     private long id;
     @Size(min=8)
     @NotNull
     private String name;
     @Size(min=8)
     @NotNull
     private String description;
     @NotNull
     private String priority;
     @Size(min=8)
     @NotNull
     private String location;
     private boolean completed;
     @DateTimeFormat(pattern = "dd-MM-yyyy HH:mm")
     @NotNull
     private LocalDateTime dueDate;


     //getters e setters omitidos
}

I think it’s not so relevant, but this is the controller :

@PostMapping("/dashboard/task/{id}")
public String TaskForm(@Valid @ModelAttribute("taskDTO")TaskDTO taskDTO,BindingResult bidingResult,@PathVariable("id")long id) {
    if(bidingResult.hasFieldErrors()) {
        //
    }
    Project p = projectRepository.findById(id).get();
    Task t = taskDTO.generateTask(p);
    taskRepository.save(t);
    return "main";
}

1 answer

2


To work with the new Java 8 Date API in Thymeleaf, you need two things that you can check for in your project:

1) a dependency with an extra module of Thymeleaf (Obs.: the version of this dependency must be the SAME as that of Thymeleaf currently in use in the project. This one that Linkei here is the latest).

//Se for projeto Maven
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

//Se for projeto Gradle
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-java8time', version: '3.0.1.RELEASE'

2) a specific configuration of the engine of Thymeleaf. In your case, possibly you already have this method, so simply include the indicated line:

private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.addDialect(new Java8TimeDialect()); //linha a ser adicionada
    engine.setTemplateResolver(templateResolver);
    return engine;
}

Maybe this will solve your problem. Here there are some additional information you can take a look at too.

  • 1

    I had already added and configured this dependency, finally I passed a string and converted it to the server.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.