0

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.

Fred Kibuchi
  • 123
  • 1
  • 4
  • 15

1 Answers1

1

Attribute name missing from the select tag

Following will fix the issue

<select class="form-control form-control-sm" name="roles" id="agentName">
R.G
  • 6,436
  • 3
  • 19
  • 28
  • why is the name attribute soo important than th:value element. this is working perfect yeah – Fred Kibuchi Jan 08 '20 at 11:22
  • name attribute is used in a form submission. You can read more about it here https://stackoverflow.com/questions/1397592/difference-between-id-and-name-attributes-in-html – R.G Jan 08 '20 at 11:37
  • th:value here sets the value for options available . When the form gets submitted , the selected option (value) among the options , will be submitted with the name of the select tag . – R.G Jan 08 '20 at 12:37