Skip to content

Lab 15 - Better UI For Options

Using an input text field for a fixed set of choices is annoying, so in this lab you'll convert the coffee options to checkboxes and dropdown select lists.

Note: In this lab you're a bit more on your own, so don't hesitate to ask for help if you get stuck.

Convert Size to Radio Buttons

Put Choices in Model

To put the size options into the model so it can be processed by Thymeleaf, you would do something like this:

@ModelAttribute("sizeOptions")
public List<String> coffeeSizeOptions() {
  return Arrays.asList("Small", "Medium", "Large");
}

However, we already have Enums for the options. There's a way to convert an Enum to a list of strings as you can see in this test method (try it out!):

@Test
public void enumAsStrings() throws Exception {
  List<String> enumNames = Stream.of(SizeOption.values())
                                 .map(Enum::name)
                                 .map(String::toLowerCase)
                                 .map(StringUtils::capitalize)
                                 .collect(Collectors.toList());
  assertThat(enumNames)
      .containsExactlyInAnyOrder("Small", "Medium", "Large");
}

Thymeleaf Radios

To have Thymeleaf generate the radio buttons, you use the th:each along with an HTML input paired with its label. For example:

<div th:each="sizeOption : ${sizeOptions}" class="optionItem">
  <input type="radio"
         th:field="*{size}"
         th:value="${sizeOption}"/>
  <label
      th:for="${#ids.prev('size')}"
      th:text="${sizeOption}">Small</label>
</div>

Note that the th:field still matches the size property of the CoffeeOrderForm DTO, so no changes need to be made in processing the order.

Replace Text Input

Given the above information, replace the input field for the Size option with the radio buttons.

Try it out and make sure it works before moving on.

Replace Others With Radios

Now replace the creamer and sweetener text inputs with radio buttons as well.

Try it out and make sure it works before moving on.

Sometimes a dropdown list is preferable to radio buttons. To create dropdowns with Thymeleaf, you'll use select and option tags. For example:

<select th:field="*{selectedKind}">
  <option th:each="coffeeKind : ${coffeeKinds}"
          th:value="${coffeeKind}"
          th:text="${coffeeKind}">Coffee Kind
  </option>
</select>

Here, the possible options are coming from the coffeeKinds property list in the model, and the choice that the user makes will be stored in the name specified by the th:field attribute, i.e., selectedKind.

Use Dropdown for Size

Using the above example, replace the radio buttons for Size with a dropdown.


Once you've completed the above steps,
check in with the instructor to review your code.