Search code examples
javaspringthymeleaf

Update the page and radio button is disappeared in html


I made form in Thymeleaf.Radio button have problem. When I move to the page and press update button(従業員の登録),then radio button is disappeared. Other column show error message.But radio button only disappeared. How fix it?

createUserForm.html

<form th:object="${user}" class="form-horizontal" id="add-owner-form"
    method="post">
    <div class="form-group">
        <label class="control-label"><abbr title="required">*</abbr>
            Radio</label>
        <div class="radio" th:each="item : ${radioItems}">
            <label> <input type="radio" name="admin_flag"
                th:value="${item.value}" th:text="${item.key}" th:field="*{admin_flag}">radio</input>
            </label>
        </div>
        <span th:if="${#fields.hasErrors('admin_flag')}" th:errors="*{admin_flag}"
            class="help-block">error!</span>
    </div>
    <p>
        <input type="submit" value="従業員情報の登録" />
    </p>
</form>

Controller

@Controller
public class UserController {

    @GetMapping("/users/new")
    public String initCreationForm(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        model.addAttribute("radioItems", RADIO_ITEMS);
        return "user/createUserForm";
    }

    @PostMapping("/users/new")
    public String processCreationForm(@Validated User user, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "user/createUserForm";
        } else {
            userService.saveUser(user);
            model.addAttribute("user", user);
            return "redirect:/users/show/" + user.getId();
        }
    }

    final static Map<String, String> RADIO_ITEMS = Collections.unmodifiableMap(new LinkedHashMap<String, String>() {
        {
            put("権限者", "0");
            put("一般", "1");
        }
    });
}

Model

@Table(name = "users")
@Entity
public class User implements Serializable {

    @Column(nullable = false, columnDefinition = "tinyint(1) default 1")
    private boolean admin_flag = false;
}

Before press button enter image description here

After enter image description here


Solution

  • It is because in your POST controller you forgot to add:

    model.addAttribute("radioItems", RADIO_ITEMS);
    

    to your model. Without any value the div tag is not displayed.