Handling Null Radio Button Data in Thymeleaf and Spring MVC

I know there are alternative approaches to handling empty child objects when in the form of radio buttons in Thymeleaf, and perhaps better ones. This post describes how we’re doing it in NixMash Spring v0.1.9 where we have added Contact Hobbies to our Update Contact Form.

Using straight-up Thymeleaf posting to Spring MVC with no client-side JavaScript functions on submit, when all Hobby radio buttons are cleared Contact.Set<Hobby> will be null. That causes a few issues like the lack of a Hobbies Model that Thymeleaf requires to generate the radio buttons shown here.

<table class="table table-striped" th:if="${!contact['new']}">
        <td class="col-sm-1">
            <label th:text="#{contactform.hobbies.title}">[Hobbies]</label>
        <td class="col-sm-2">
            <ul class="hobbyList">
                <li th:each="hobby : ${hobbies}">
                    <input type="checkbox" th:field="*{hobbies}" th:value="${hobby.hobbyId}"/>
                    <label th:for="${#ids.prev('hobbies')}" th:text="#{${hobby}}">[Hobby]</label>

The resulting postback would look like this, with no hobbies appearing (that awful empty space above the buttons…)

A Contact Form Validator

You may recall from prior posts that we’re using a custom ContactFormValidator on the Contact Form, the validator is @AutoWired in the ContactController Constructor and Binder Initialized for the “contact” model.

We’ve got a validator method in the class which checks if form.getHobbies() == null and if so rejects the form. We’re requiring the user to select at least one hobby, in other words. So with the error registered we can send the user back to the Contact form page with the validator’s error message.

Here’s our controller method where you’ll notice that we’ll send a fresh list of Hobbies for the Contact Model so Thymeleaf can generate an empty radio button list.

Testing Null Hobbies

For sake of completeness here is our test on sending an empty list of radio buttons to our Controller ContactUpdate() method. The test confirms we are returned to the Contact Form view and an error has been registered with our Contact model.

The source code discussed in this post is available in the v0.1.9 Branch of NixMash Spring on GitHub.