# Building an application with Shadleaf - part 3

Author: [Wim Deblauwe](https://www.wimdeblauwe.com/about/) | Published: 2026-11-30 | Topics: thymeleaf, spring-boot | Canonical: https://www.wimdeblauwe.com/blog/2026/11/30/building-an-application-with-shadleaf---part-3/

In [part 2](https://www.wimdeblauwe.com/blog/2026/11/23/building-an-application-with-shadleaf---part-2/) of _Building an application with Shadleaf_, we built a table of expenses with sorting and pagination. In this part, we will build the form to create and edit an expense, with server-side validation, all without writing any JavaScript.

The form uses most of Shadleaf’s form components: an [input group](https://shadleaf.dev/current/components/input-group/) with a currency addon for the amount, a [date picker](https://shadleaf.dev/current/components/date-picker/), a [select](https://shadleaf.dev/current/components/select/) for the category, a [combobox](https://shadleaf.dev/current/components/combobox/) for the project, a [switch](https://shadleaf.dev/current/components/switch/) and a [textarea](https://shadleaf.dev/current/components/textarea/). Each of those components is placed inside a [field](https://shadleaf.dev/current/components/field/), which adds all the parts of a good form element: a label, a description and validation errors.

After saving the expense, we redirect back to the list and show a [toast](https://shadleaf.dev/current/components/toast/).

## Projects

An expense has an optional link to a project for which the expense was needed. Until now, this was just a nullable String, but now we will make this a real link to a separate `Project` entity.

This will allow us to select an existing project in a combobox when editing an expense in the form.

With `Project` an entity of its own, we have `Expense` refer to its project by its id:

**src/main/java/com/wimdeblauwe/examples/spendleaf/expense/Expense.java**

```java
@Entity
public class Expense extends AbstractEntity<ExpenseId> {
    ...
    private @Nullable ProjectId project;
    ...
}
```

The entity, the database migration and the repository query that sorts the expenses on the name of their project are standard Spring Boot. See the [part-3 sources](https://github.com/wimdeblauwe/blog-example-code/tree/part-3/spendleaf) on GitHub for the details.

> [!NOTE]
> The reason I use `ProjectId` and not `Project` here is that both `Expense` and `Project` are [aggregate roots](https://martinfowler.com/bliki/DDD_Aggregate.html) with different lifecycles. Only linking different aggregate roots via ids avoids a lot of JPA/Hibernate issues.

For the HTML side, we need the projects in two places: as the options of the combobox in the form, and to show the name of the project in the table, as an expense only has the id of its project. Two general utility classes will help implement this:

**src/main/java/com/wimdeblauwe/examples/spendleaf/infrastructure/web/IdAndName.java**

```java
public record IdAndName(UUID id, String name) { (1)
}
```

1. `IdAndName` is a record that combines the id (primary key) of an entity with its name.

**src/main/java/com/wimdeblauwe/examples/spendleaf/infrastructure/web/IdAndNameCollection.java**

```java
public class IdAndNameCollection implements Iterable<IdAndName> { (1)
    private final Map<UUID, IdAndName> values = new LinkedHashMap<>(); (2)

    public IdAndNameCollection(List<IdAndName> values) {
        for (IdAndName value : values) {
            this.values.put(value.id(), value);
        }
    }

    public @Nullable String nameOf(@Nullable EntityId<UUID> id) { (3)
        if (id == null) {
            return null;
        }
        IdAndName value = values.get(id.getId());
        return value != null ? value.name() : null;
    }

    @Override
    public Iterator<IdAndName> iterator() {
        return values.values().iterator();
    }
}
```

1. The `IdAndNameCollection` is `Iterable` so a Thymeleaf template can loop over it with `th:each`.
2. A `LinkedHashMap` keeps the order in which the values were given, so the options of the combobox will be sorted the same way as the list.
3. `EntityId` is the interface that [JPearl](https://github.com/wimdeblauwe/jpearl)'s id classes implement, so this works for the id of any entity, not only for a `ProjectId`.

The class is not tied to projects, so we can use it again for other entities that we need to show in a select or a combobox.

The controller adds the projects to the model with a `@ModelAttribute` method:

**src/main/java/com/wimdeblauwe/examples/spendleaf/expense/web/ExpenseController.java**

```java
@ModelAttribute("projects")
public IdAndNameCollection projects() {
    return new IdAndNameCollection(getProjects.execute().stream()
                                           .map(project -> new IdAndName(project.getId().getId(), project.getName()))
                                           .toList());
}
```

A `@ModelAttribute` method adds its result to the model of every request the controller handles, so the projects are available on the expenses page now, and in the form later.

The table uses `nameOf` to show the name of the project:

**src/main/resources/templates/expenses/index.html**

```html
<td th:text="${projects.nameOf(expense.project)} ?: '—'">Atlas</td>
```

When an expense has no project, `nameOf` returns `null`, and the Elvis operator shows a dash instead.

Sorting on the Project column keeps working as before: the column still sends `sort=project`, and the repository sorts on the name of the project.

## The create expense page

The empty state we built in part 2 already had a link to `/expenses/create`. Time now to build the page behind that link.

### The form data

As explained in my [Form handling with Thymeleaf](https://www.youtube.com/watch?v=KrhANnaN-X0) video, you should not bind an entity to the form directly. Use a separate form data object so it can hold invalid input and show that input again when you re-render the page to show the error messages. That way, the user can correct their mistake(s). The entity can’t do that: an `Amount` of zero or less is rejected in its constructor, and the entity stores a `ProjectId`, not the `UUID` that the browser sends.

In this example, we use the `CreateExpenseFormData` class.

**src/main/java/com/wimdeblauwe/examples/spendleaf/expense/web/CreateExpenseFormData.java**

```java
public class CreateExpenseFormData {
    @NotBlank
    @Size(max = 200)
    private @Nullable String description;
    @NotNull
    @Positive
    @Digits(integer = 8, fraction = 2)
    private @Nullable BigDecimal amount; (1)
    @NotNull
    @PastOrPresent
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) (2)
    private @Nullable LocalDate date;
    @NotNull
    private @Nullable ExpenseCategory category;
    private @Nullable UUID project; (3)
    private boolean billable;
    @Size(max = 1000)
    private @Nullable String notes;

    public static CreateExpenseFormData withDefaults() { (4)
        CreateExpenseFormData formData = new CreateExpenseFormData();
        formData.setDate(LocalDate.now());
        return formData;
    }

    public CreateExpenseParameters toParameters() { (5)
        return new CreateExpenseParameters(description,
                                           new Amount(amount),
                                           date,
                                           category,
                                           project != null ? new ProjectId(project) : null,
                                           billable,
                                           notes);
    }

    // getters and setters omitted
}
```

1. The amount is a `BigDecimal`, as the form uses an input with `type="number"`.
2. The date picker submits ISO dates (`2026-11-30`), so we need `@DateTimeFormat` to tell Spring to use that format when binding the value.
3. The id of the selected project. When no project is selected, the combobox submits an empty string, which Spring converts to `null` for a `UUID`.
4. Factory method to create an empty form data object using today’s date, as most expenses are entered on the day itself.
5. After validation, `toParameters()` converts the form data into the parameters of the `CreateExpense` use case, with the `Amount` and `ProjectId` value objects.

> [!NOTE]
> Bean Validation is not part of the web starter, so I added `spring-boot-starter-validation` to the `pom.xml`.

A browser submits every field of a form as text, including the ones that the user left empty. When Spring binds the form, it converts that text to the type of the field in the form data class. For almost every type in the form data object (e.g. `BigDecimal`, `LocalDate`, an enum or `UUID`), Spring converts an empty value coming from the HTML form to `null` on the Java side.

The only type that is different is `String`. There, Spring keeps the empty string as it is by default. We will change that in the controller so an empty string also becomes `null`.

To actually create the expense and save it in the database, we use the `CreateExpense` use case. It uses the `CreateExpenseParameters` to create a real `Expense` entity and save it in the database. See the [part-3 sources](https://github.com/wimdeblauwe/blog-example-code/tree/part-3/spendleaf) for the use case and its `CreateExpenseParameters`.

### The controller

As usual with form handling, we need two controller methods: one using `GET` for showing the form, and one using `POST` for submitting the form data:

**src/main/java/com/wimdeblauwe/examples/spendleaf/expense/web/ExpenseController.java**

```java
@InitBinder
void initBinder(WebDataBinder binder) {
    // Trims text input, and turns an empty field into null
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); (1)
}

@ModelAttribute("categories")
public List<ExpenseCategory> categories() { (2)
    return List.of(ExpenseCategory.values());
}

@GetMapping("/create")
public String createExpenseForm(Model model) {
    model.addAttribute("expense", CreateExpenseFormData.withDefaults()); (3)
    return "expenses/edit";
}

@PostMapping("/create")
public String doCreateExpense(@Valid @ModelAttribute("expense") CreateExpenseFormData formData,
                              BindingResult bindingResult) { (4)
    if (bindingResult.hasErrors()) {
        return "expenses/edit"; (5)
    }

    createExpense.execute(formData.toParameters());
    return "redirect:/expenses"; (6)
}
```

1. The `StringTrimmerEditor` removes the spaces around text input. With `true`, it also converts an empty `String` field to `null`, like Spring already does for the other types. Without it, empty notes would be stored as an empty string instead of `null`.
2. The options for the category select. Like the projects, they are a `@ModelAttribute`, so they are also available when the form is shown again with errors.
3. The form data is added to the model as `expense`. The template binds to that name, and Spring uses it in the message codes of the validation errors.
4. `@Valid` runs Bean Validation on the form data. The `BindingResult` must come directly after it, otherwise Spring throws an exception instead of handing us the errors.
5. With errors, we render the same template again. The form data still holds what the user entered, and the `BindingResult` holds the errors.
6. Without errors, we redirect to the list of expenses (Post/Redirect/Get), so refreshing the page does not submit the form a second time.

> [!TIP]
> See [Form handling with Thymeleaf](https://www.youtube.com/watch?v=KrhANnaN-X0) on YouTube for a video about the Post/Redirect/Get pattern.

### The template

The template is `expenses/edit.html`. For now, it only creates expenses, but we will use the same template for editing an expense later in this post.

Let’s start with the form itself and its first field:

**src/main/resources/templates/expenses/edit.html**

```html
<form id="expense-form"
      th:object="${expense}"
      th:action="@{/expenses/create}"
      method="post"
      novalidate (1)
      class="max-w-2xl">
<sl:card>
    <sl:card-content>
        <sl:field-group> (2)
            <sl:field th:field="*{description}"> (3)
                <sl:field-label>Description</sl:field-label>
                <sl:input placeholder="Hotel Ghent, 2 nights"/>
                <sl:field-error/>
            </sl:field>

            <!-- the other fields -->
        </sl:field-group>
    </sl:card-content>
    <sl:card-footer class="justify-end gap-2">
        <sl:button as="a" variant="outline" th:href="@{/expenses}">Cancel</sl:button>
        <sl:button type="submit">Create expense</sl:button> (4)
    </sl:card-footer>
</sl:card>
</form>
```

1. `th:object` selects the form data, so `*{…​}` expressions refer to its fields. `novalidate` turns off the validation of the browser, so all validation happens on the server.
2. `<sl:field-group>` stacks the fields with even spacing.
3. The `<sl:field>` groups all elements of a single value that is editable in the form. The `th:field` attribute refers to the property of the Java form data object.
4. Make the `<sl:button>` a submit button so the form can be submitted.

The `<sl:field>` is where Shadleaf does the work. It takes the `th:field` and hands it to the parts inside it: the input gets the `name`, `id` and `value`, and the label gets a `for` that points at the input. The first time the page renders, this is the HTML for the description:

```html
<div class="field">
  <label class="label field-label" for="description">Description</label>
  <input class="input" type="text" placeholder="Hotel Ghent, 2 nights"
         id="description" name="description" value="">
</div>
```

When the form comes back with an error on the description, the same template renders this:

```html
<div class="field" data-invalid="true">
  <label class="label field-label" for="description">Description</label>
  <input class="input" type="text" aria-invalid="true" placeholder="Hotel Ghent, 2 nights"
         id="description" aria-describedby="description-error" name="description" value="">
  <div class="field-error" id="description-error">must not be blank</div>
</div>
```

The field gets `data-invalid` and the input gets `aria-invalid`, which Shadleaf’s CSS uses to show the error colors. The input’s `aria-describedby` points at the error message, so a screen reader reads the message when the user reaches the input.

`<sl:field-error>` renders the error messages of the field, or nothing at all if there are no errors. All of that comes from the single `th:field`, without a `th:if` or `#fields.hasErrors(…​)` in our template.

Navigate to [http://localhost:8080/expenses/create](http://localhost:8080/expenses/create) to view the form:

[![shadleaf part 03 01 create expense](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-01-create-expense.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-01-create-expense.webp)

Submitting with missing values shows the validation errors:

[![shadleaf part 03 02 validation errors](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-02-validation-errors.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-02-validation-errors.webp)

We currently only show the 'New expense' button if there are no expenses, but we also need this button when the table is showing. Add a button above the table for this:

**src/main/resources/templates/expenses/index.html**

```html
<div class="mb-4 flex justify-end">
    <sl:button as="a" th:href="@{/expenses/create}">New expense</sl:button>
</div>
```

[![shadleaf part 03 03 button on list](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-03-button-on-list.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-03-button-on-list.webp)

## The other fields

The `description` field showed how a `<sl:field>` works. All other fields follow the same pattern: `th:field` on the `<sl:field>`, and a control inside it. This section explains the other controls in more detail.

### Amount

The amount is a number input with a euro sign in front of it. The [`<sl:input-group>`](https://shadleaf.dev/current/components/input-group/) puts text, icons or buttons inside the border of an input:

```html
<sl:field th:field="*{amount}">
    <sl:field-label>Amount</sl:field-label>
    <sl:input-group>
        <sl:input-group-input type="number"
                              step="0.01"
                              min="0.01"
                              inputmode="decimal"
                              placeholder="0.00"/> (1)
        <sl:input-group-addon>
            <sl:input-group-text>€</sl:input-group-text>
        </sl:input-group-addon> (2)
    </sl:input-group>
    <sl:field-error/>
</sl:field>
```

1. The `<sl:input-group-input>` takes the `th:field` of the `<sl:field>`, like the `<sl:input>` of the description did. We also add `inputmode="decimal"` which shows a numeric keyboard with a decimal separator on phones.
2. It might be surprising that the euro sign is shown first, but comes after the `<sl:input-group-input>` in the template. The reason for this is that it makes the input first in the tab order, and a screen reader will also read it first. Because the default `align` of the addon is `inline-start`, it is still shown visually before the number.

When the amount has an error, the red border goes around the whole input group, not only around the number.

### Two fields side by side

The amount and the date are short fields, so we can put them side by side on a wider screen. Using Tailwind CSS, we create a two-column grid:

```html
<div class="grid gap-6 sm:grid-cols-2">
    <sl:field th:field="*{amount}">...</sl:field>
    <sl:field th:field="*{date}">...</sl:field>
</div>
```

The category and the project use the same grid on the next row. As mentioned in [part 1](https://www.wimdeblauwe.com/blog/2026/11/16/building-an-application-with-shadleaf/), we use Tailwind CSS utilities for the markup of the application itself, like this layout.

### Date

The [`<sl:date-picker>`](https://shadleaf.dev/current/components/date-picker/) is a button that opens a calendar:

```html
<sl:field th:field="*{date}">
    <sl:field-label>Date</sl:field-label>
    <sl:date-picker/>
    <sl:field-error/>
</sl:field>
```

The value is kept in a date input inside the date picker. That input takes the `th:field`, and submits the date in the ISO format, which is why the form data has `@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)` on the date.

The button shows the selected date in the locale of the page. The server renders that text, and the browser formats it again in the same way after the user picks another date. The [`format`](https://shadleaf.dev/current/components/date-picker/#the-buttons-text) prop selects the style: `short`, `medium`, `long` (the default) or `full`.

[![shadleaf part 03 04 date picker](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-04-date-picker.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-04-date-picker.webp)

### Category

For the category (an enum), we use a [`<sl:select>`](https://shadleaf.dev/current/components/select/):

```html
<sl:field th:field="*{category}">
    <sl:field-label>Category</sl:field-label>
    <sl:select placeholder="Select a category"> (1)
        <sl:select-item th:each="category : ${categories}"
                        th:value="${category}">[[#{|ExpenseCategory.${category}|}]]</sl:select-item> (2)
    </sl:select>
    <sl:field-error/>
</sl:field>
```

1. The `placeholder` is shown until the user selects a category. It is rendered as a hidden option with an empty value, so a form that is submitted without a category fails on `@NotNull`.
2. One item for each category from the `categories` model attribute, with the translated name of the category as its content. It is important to use a Thymeleaf inline expression (`[[…​]]`) here, and not `th:text`: `th:text` would replace the check mark that the selected item shows.

Shadleaf has three components to choose one value from a list: `<sl:select>` for a short list, `<sl:native-select>` to leave the list to the operating system, which is nice on phones, and `<sl:combobox>` for a list that people would rather search. See [Select, native select or combobox?](https://shadleaf.dev/current/components/select/#select-native-select-or-combobox) for when to use which one.

### Project

The project field uses a [`<sl:combobox>`](https://shadleaf.dev/current/components/combobox/), so the user can type a few letters to find a project:

```html
<sl:field th:field="*{project}">
    <sl:field-label>Project</sl:field-label>
    <sl:combobox placeholder="No project" show-clear> (1)
        <sl:combobox-item th:each="project : ${projects}"
                          th:value="${project.id}">[[${project.name}]]</sl:combobox-item> (2)
    </sl:combobox>
    <sl:field-error/>
</sl:field>
```

1. The `placeholder` is the option with an empty value, which Spring binds as `null`, which in this case means the expense should not be linked to a project. `show-clear` adds an `x` icon to remove the project again.
2. The `IdAndNameCollection` from the beginning of this post is `Iterable`, so `th:each` can loop over it.

Like the select, the combobox renders a real `<select>` element. JavaScript replaces it with a text input that filters the list while the user types.

> [!TIP]
> For lists that are too long to put in the page, the combobox can also load its options from the server while the user types, with [the `search-url` prop](https://shadleaf.dev/current/components/combobox/#options-from-the-server).

[![shadleaf part 03 05 combobox](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-05-combobox.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-05-combobox.webp)

### Billable

Whether the expense can be charged to the client is a yes-or-no question, so we use a [`<sl:switch>`](https://shadleaf.dev/current/components/switch/):

```html
<sl:field th:field="*{billable}" orientation="horizontal"> (1)
    <sl:switch/>
    <sl:field-content> (2)
        <sl:field-label>Billable</sl:field-label>
        <sl:field-description>Charge this expense to the client of the project.</sl:field-description>
    </sl:field-content>
</sl:field>
```

1. With `orientation="horizontal"`, the switch comes first, and the label is shown next to it.
2. `<sl:field-content>` stacks the label and the description next to the switch.

A switch is a checkbox, which comes with two details that Shadleaf and Spring handle for us:

- A browser does not submit a checkbox that is turned off. `th:field` adds a hidden `_billable` input, so Spring knows the field was in the form and sets `billable` to `false`.
- Spring gives a checkbox a numbered id (`billable1`), so that several checkboxes for one field get different ids. Inside a `<sl:field>`, the switch gets `billable` as its id, so the `for` of the label points at it.

This is the HTML it renders:

```html
<div class="field" data-orientation="horizontal">
  <input type="checkbox" role="switch" class="switch" id="billable"
         aria-describedby="billable-description" name="billable" value="true">
  <input type="hidden" name="_billable" value="on"/>
  <div class="field-content">
    <label class="label field-label" for="billable">Billable</label>
    <p class="field-description" id="billable-description">Charge this expense to the client of the project.</p>
  </div>
</div>
```

### Notes

The last field is a [`<sl:textarea>`](https://shadleaf.dev/current/components/textarea/) for notes:

```html
<sl:field th:field="*{notes}">
    <sl:field-label>Notes</sl:field-label>
    <sl:textarea rows="3"/>
    <sl:field-description>Optional. Anything the approver should know.</sl:field-description>
    <sl:field-error/>
</sl:field>
```

The notes field has a description and an error message. The textarea’s `aria-describedby` points at the description, and also at the error message when there is one, so a screen reader reads both. In browsers that support it, the textarea grows with its content, and `rows` sets its starting height.

### The complete form

With all fields in place, the form looks like this:

[![shadleaf part 03 06 complete form](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-06-complete-form.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-06-complete-form.webp)

Every control in the form is a real form element: an input, a select or a checkbox. The browser submits the form like any other HTML form, and Spring binds it to the form data. Shadleaf only adds JavaScript to make the controls nicer to use, like the calendar of the date picker and the filtering of the combobox.

## Validation messages

When we submitted the empty form before, the fields showed the default messages of Hibernate Validator:

[![shadleaf part 03 02 validation errors](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-02-validation-errors.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-02-validation-errors.webp)

"must not be null" is not something we want to show to the users of our application. Spring looks up the message of a validation error in `messages.properties` before it falls back to the default message. It tries a few message codes, from specific to generic. For the `@NotBlank` on the description of the `expense` form, the most specific one is `NotBlank.expense.description`: the name of the constraint, the name of the model attribute and the name of the field.

So to have nicer error messages, we add a message for each constraint on the form data:

**src/main/resources/i18n/messages.properties**

```properties
NotBlank.expense.description=Enter a description.
Size.expense.description=The description can be at most {1} characters.
NotNull.expense.amount=Enter an amount, like 12.50.
Positive.expense.amount=The amount must be more than zero.
Digits.expense.amount=The amount can have at most {1} decimals.
NotNull.expense.date=Pick the date of the expense.
PastOrPresent.expense.date=The date can't be in the future.
NotNull.expense.category=Select a category.
Size.expense.notes=The notes can be at most {1} characters.
```

The placeholders get the attributes of the constraint, in alphabetical order after the name of the field in `{0}`. So `{1}` is the `max` of `@Size`, and the `fraction` of `@Digits`.

The amount uses an input with `type="number"`, and such an input never sends text that is not a number. When the user types something the browser can’t read as a number, it sends an empty value instead, and the amount fails on `@NotNull`. So the message for `NotNull.expense.amount` has to make sense in that case as well, which is why it says how to enter an amount, and not only that the amount is missing.

> [!TIP]
> Always include the expected format in the error message if an input needs to adhere to a certain format. There is nothing more frustrating for a user than trying to guess what the expected format is when filling in a form.

With these messages, the form looks a lot friendlier:

[![shadleaf part 03 07 validation messages](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-07-validation-messages.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-07-validation-messages.webp)

## Error summary

On a long form, the user might not see all errors at once. The [`<sl:form-errors>`](https://shadleaf.dev/current/components/form-errors/) component shows a summary of the errors at the top of the form. We add it as the first element of the `<sl:field-group>`:

**src/main/resources/templates/expenses/edit.html**

```html
<form id="expense-form" th:object="${expense}" th:action="@{/expenses/create}" method="post" novalidate
      class="max-w-2xl">
    <sl:card>
        <sl:card-content>
            <sl:field-group>
                <sl:form-errors show="all" autofocus/> (1)
                <sl:field th:field="*{description}">
                ...
```

1. `<sl:form-errors>` reads the errors of the form data that `th:object` selects. It renders nothing while there are no errors.

By default, `<sl:form-errors>` only shows the errors that belong to the whole form, and not to a single field, like an error from `bindingResult.reject(…​)` in the controller. Our form has no such errors, so we use `show="all"` to list the errors of the fields as well. Each field still shows its own error next to its control.

The summary lists the messages without the label of the field they belong to. That is another reason to write the messages as complete sentences, like "Enter a description.", and not as "must not be blank".

`autofocus` moves the focus to the summary when the form comes back with errors, so a screen reader reads the summary right away. The user can then press the Tab key to continue to the fields. We only do this because the form is the only thing on the page. On a page with more content, moving the focus would skip the heading of the page.

The title of the summary is "There is a problem" by default. To change it for all forms, add the `sl.form-errors.title` key to `messages.properties`, or use the `title` attribute to change it for a single form.

[![shadleaf part 03 08 error summary](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-08-error-summary.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-08-error-summary.webp)

## A toast after saving

When the form is valid, the controller saves the expense and redirects to the list of expenses. The new expense is somewhere in that list, but the user gets no confirmation that it was saved. A [toast](https://shadleaf.dev/current/components/toast/) is a good fit for that: a short message in a corner of the page that goes away by itself.

### The toaster

The toasts are shown in a `<sl:toaster>`. There is normally one toaster for the whole application, so we add it to the layout, at the end of the `<body>`:

**src/main/resources/templates/layout/main.html**

```html
<body>
...
<sl:toaster>
    <sl:toast th:each="toast : ${toasts}"
              th:title="${toast.title}"
              th:description="${toast.description}"
              th:variant="${toast.variant}"
              th:duration="${toast.duration}"/> (1)
</sl:toaster>
</body>
```

1. The toaster renders a `<sl:toast>` for each toast in the `toasts` model attribute. Most pages don’t have that attribute, and then the toaster is empty.

### The flash attribute

The toast has to be shown on the page after the redirect, not on the page that handles the form submission. A model attribute does not survive a redirect, but a flash attribute does: Spring keeps it in the session, and adds it to the model of the next request.

**src/main/java/com/wimdeblauwe/examples/spendleaf/expense/web/ExpenseController.java**

```java
@PostMapping("/create")
public String doCreateExpense(@Valid @ModelAttribute("expense") CreateExpenseFormData formData,
                              BindingResult bindingResult,
                              RedirectAttributes redirectAttributes) { (1)
    if (bindingResult.hasErrors()) {
        return "expenses/edit";
    }

    Expense expense = createExpense.execute(formData.toParameters()); (2)
    redirectAttributes.addFlashAttribute("toasts", List.of( (3)
            Toast.success("Expense created").withDescription(expense.getDescription())));
    return "redirect:/expenses";
}
```

1. Add `RedirectAttributes` as a parameter of the method to be able to add a flash attribute.
2. The use case returns the created expense, so we can use its description in the toast.
3. `Toast` is a record from Shadleaf with a title, an optional description, a variant and an optional duration. `Toast.success(…​)` sets the `success` variant. The flash attribute is a list, so a single request can show more than one toast.

After the redirect, the list of expenses renders the toast in the toaster, and the toast closes itself after 5 seconds. The toaster also has a live region, so a screen reader announces the toast without the user having to look for it.

[![shadleaf part 03 09 toast](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-09-toast.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-09-toast.webp)

In part 5, we will create and edit expenses with htmx, without a redirect. The same `Toast` record will then travel in a response header instead of a flash attribute, and the toaster in the layout will show it in the same way.

## Editing an expense

The last step is editing an existing expense. On the Java side, this follows the same pattern as creating one:

- The fields and their validation annotations moved from `CreateExpenseFormData` to an `AbstractExpenseFormData`. `CreateExpenseFormData` and the new `EditExpenseFormData` extend it. `EditExpenseFormData` also has the id of the expense, and a static `fromExpense(Expense)` method that fills the form data from an existing expense.
- The `GetExpense` and `EditExpense` use cases load and update the expense.
- The controller handles `GET` and `POST` on `/expenses/{id}`, and redirects to the list with an "Expense updated" toast.
- All handlers add an `editMode` attribute to the model: `EditMode.CREATE` for a new expense and `EditMode.UPDATE` for an existing one.

See the [part-3 sources](https://github.com/wimdeblauwe/blog-example-code/tree/part-3/spendleaf) for the details.

### Linking from the table

The description in the table of expenses becomes a link to the edit page:

**src/main/resources/templates/expenses/index.html**

```html
<td>
    <a th:href="@{/expenses/{id}(id=${expense.id.asString()})}" th:text="${expense.description}"
       class="font-medium hover:underline">Hotel Ghent, 2 nights</a>
</td>
```

### One template for both

Because the create page and the edit page are mostly the same, we use the same `expenses/edit.html` template. For the few things that differ, the template uses the `editMode` enum to switch between options:

**src/main/resources/templates/expenses/edit.html**

```html
<html xmlns:th="http://www.thymeleaf.org" xmlns:sl="https://shadleaf.dev/sl"
      th:replace="~{layout/main :: layout(${editMode.name() == 'UPDATE'} ? 'Edit expense' : 'New expense', ~{::breadcrumb}, ~{::#page-content})}"> (1)
...
<sl:breadcrumb-page>[[${editMode.name() == 'UPDATE'} ? 'Edit expense' : 'New expense']]</sl:breadcrumb-page> (2)
...
<form id="expense-form" th:object="${expense}" method="post" novalidate
      th:action="${editMode.name() == 'UPDATE'} ? @{/expenses/{id}(id=${expense.id})} : @{/expenses/create}" (3)
      class="max-w-2xl">
    ...
    <sl:button type="submit">[[${editMode.name() == 'UPDATE'} ? 'Save expense' : 'Create expense']]</sl:button> (4)
    ...
</form>
```

1. The title of the page, which the layout uses for the `<title>` and the heading.
2. The last item of the breadcrumb.
3. The form posts to `/expenses/{id}` when editing, and to `/expenses/create` when creating. `${expense.id}` only exists on `EditExpenseFormData`, but Thymeleaf only evaluates the branch of the condition that it needs.
4. The text of the submit button. Like the select items, the button gets its text as content.

### The fields show the current values

For editing, the form needs to show the current values initially. The controller puts an `EditExpenseFormData` with the values of the expense in the model, and the `th:field` of each `<sl:field>` does the rest:

- The inputs for the description, the amount and the notes get the current value.
- The date picker shows the date of the expense on its button, formatted in the locale of the page.
- The select and the combobox mark the option of the current category and project as selected.
- The switch is turned on when the expense is billable.

None of this needs any code in the template that is specific to editing. Because the components render real form elements, Spring’s data binding works for them as it works for plain HTML.

[![shadleaf part 03 10 edit expense](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-10-edit-expense.webp)](https://www.wimdeblauwe.com/images/2026/11/shadleaf-part-03-10-edit-expense.webp)

When the user saves the form, the controller redirects to the list of expenses, and the toaster shows "Expense updated".

## Conclusion

In this part, we built a form to create and edit an expense. Thanks to `<sl:field>`, a single `th:field` wires up the label, the description, the error messages and the accessibility attributes of each control. And because every Shadleaf form component renders a real form element, Spring binds and validates the form like any other HTML form.

In the next part, we will use htmx to make the table of expenses feel faster: live search, filters, and sorting and paging without reloading the whole page.

See [spendleaf](https://github.com/wimdeblauwe/blog-example-code/tree/part-3/spendleaf) on GitHub for the full sources of this part.

If you have any questions or remarks, feel free to post a comment at [GitHub discussions](https://github.com/wimdeblauwe/wimdeblauwe.com/discussions).

