Search code examples
mysqlspringspring-bootspring-data-jpathymeleaf

How to Save a Role from Thymeleaf using in Spring Boot?


Hello buddies, i have two models, User and Role. i have inserted three roles(ADMIN, CUSTOMER, DEALER) in table Roles. I have made these roles available to Thymeleaf User Type field to be chosen during registration.

Controller Model Attribute for roles.

@ModelAttribute("roles")

public List<Role> initializeRoles(){
    List<Role> roles = roleRepository.findAll();

    return roles ;
}

Then here is my thymeleaf to display the available roles for user to choose during registration.


 <div class="col-1.5">
        <label th:for="roles"> User Type: </label>
        <select class="form-control form-control-sm" id="agentName">
            <option value="">Select User Type</option>
            <option th:each="initializeRoles:${roles}"
                    th:value="${initializeRoles.id}"
                    th:text="${initializeRoles.name}"
            >
            </option>
        </select>
    </div>

Finally here is my User Service to submit registration data input by the user:

public void save(User user) {
        user.setEnabled(false);
        user.setPword(new BCryptPasswordEncoder().encode(user.getPword()));
        user.setRoles(user.getRoles());
        userRepository.save(user);
    }

i'm expecting the role selected from user type field to be submitted and assigned as a role to that user. however, the rest of user data is successfully persisted except the selected role. Where i'm i going wrong?

The database output after data is submitted to my tables.


Solution

  • Attribute name missing from the select tag

    Following will fix the issue

    <select class="form-control form-control-sm" name="roles" id="agentName">