0

Thymeleaf

Im trying to bind a variable called 'permitirAcesso' to thymeleaf. When I use th:checked, it shows the value correctly. When I use th:field, it doesnt bind. What should I do?

I investigated and th:text shows the correct value. Ive also tried changing the variable name, but it still doesnt work. Ive also tried to use a common html checkbox, it still doesnt bind.

Ive simplified the page and removed everything except the form and the malfunction persists. It works with th:checked but fails to bind with th:field.

Here's my code:

<head>
    <meta charset="UTF-8"/>

</head>
<body>
    <form id="formulario" th:action="@{/painel-do-administrador/usuarios/salvar}" th:object="${usuario}" method="POST" class="action-buttons-fixed">
        <input  type="checkbox"  name="permitirAcesso" id="permitirAcesso" th:field="*{permitirAcesso}" />

        <input  type="checkbox"  name="permitirAcesso" id="permitirAcesso" th:checked="*{permitirAcesso}" />
    </form>
</body>

My Java Code:

@Entity
@Table(name = "users")
public class User implements UserDetails, Comparable<User> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "O nome não pode ser nulo")
    @NotNull(message = "O nome não pode ser nulo")
    @Column(name = "username", nullable = false, length = 512, unique = true)
    private String username;


    @Column(name = "nome_completo", updatable = true, nullable = false)
    private String nomeCompleto;

    @Column(name = "password", updatable = true, nullable = false)
    private String password;

    @Column(name = "ultimo_acesso")
    private ZonedDateTime ultimoAcesso;

    @Email(message = "Insira uma e-mail válido")
    @Column(name = "email", updatable = true, nullable = false)
    private String email;

    @Column(name = "permitir_acesso")
    private boolean permitirAcesso;

    @Lob
    @Column(name = "avatar", columnDefinition = "BLOB")
    private byte[] avatar;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "users_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();

    public User() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getNomeCompleto() {
        return nomeCompleto;
    }

    public void setNomeCompleto(String nomeCompleto) {
        this.nomeCompleto = nomeCompleto;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public ZonedDateTime getUltimoAcesso() {
        return ultimoAcesso;
    }

    public void setUltimoAcesso(ZonedDateTime ultimoAcesso) {
        this.ultimoAcesso = ultimoAcesso;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isPermitirAcesso() {
        return permitirAcesso;
    }
    
    public String getPermitirAcessoString() {
        if (permitirAcesso) {
            return "Sim";
        } else {
            return "Não";
        }
    }

    public void setPermitirAcesso(boolean permitirAcesso) {
        this.permitirAcesso = permitirAcesso;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void addRole(Role role) {
        this.roles.add(role);
    }

    public boolean hasRole(Role role) {
        Iterator<Role> iterator = this.roles.iterator();
        while (iterator.hasNext()) {
            if (role.equals(iterator.next())) {
                return true;
            }
        }
        return false;
    }

    public boolean hasRole(String roleName) {
        for (Role role : this.roles) {
            if (role.getName().equals(roleName)) {
                return true;
            }
        }

        return false;
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.emptyList();
    }

    @Override
    public int compareTo(User o) {
        return getEmail().compareToIgnoreCase(o.getEmail());
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return isPermitirAcesso();
    }



}
KenobiBastila
  • 539
  • 4
  • 16
  • 52
  • 1
    `th:field` is not a straight replacement for `th:checked`. Have you set up your `th:object` correctly? (What you've shown from your code isn't enough -- we at least need the form tag.) – Metroids Jun 14 '22 at 14:20
  • I added the code. I did set the th:object correctly. – KenobiBastila Jun 14 '22 at 14:25
  • Also if I Insert the th field, th:checked stops working. Also, if I change the variable name on thymeleaf only, it complains it cant find the bean. Im starting to think this is a bug with thymeleaf? – KenobiBastila Jun 14 '22 at 15:15
  • 1
    It's pretty unlikely it's a bug in thymeleaf. In fact when I copy your code into a simple spring boot app, it works as you can see [here (the top is viewing the source in a browser, the bottom is the thymeleaf code)](https://i.stack.imgur.com/0QJcv.png). You can see both elements have `checked="checked"`. – Metroids Jun 14 '22 at 16:07

1 Answers1

0

Ok. This was a stupid mistake of mine. So what happened is that I had a Boolean Converter that converted Boolean to String. Removing the converter, fixed the issue.

KenobiBastila
  • 539
  • 4
  • 16
  • 52