Please excuse me if this question already exists. But unfortunately I can't find anything about it.
I would like to move the form into a fragment so that the layout always remains the same.
But unfortunaly it doesn't work. Thymeleaf says Neither BindingResult nor plain target object for bean name 'objectForForm' available as request attribute
When i remove the lines in input with the comments // this line
it works.
When i rename objectForForm
in the form header to shoppingListCreateRequest
it will work.
But I want to use it with different dtos. Otherwise it does not make sense to extract it.
Is there a way?
Here is the code: create.html. The file called by the controller:
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
th:replace="~{layout::layout(~{::header},~{::main},~{::footer})}">
<header th:replace="~{fragment/header :: navigationList('Create Shoppinglist')}"></header>
<main>
<div th:replace="~{fragment/form :: formWithContent(
~{fragment/shopping-list/input :: create},
shoppingListCreateRequest)}">
</div>
</main>
<footer th:replace="~{fragment/footer :: empty()}"></footer>
</html>
form:
<div th:fragment="formWithContent(inputs, objectForForm)">
<form th:action="@{/happyEat/shopping-lists/create}"
th:method="POST"
th:object="${objectForForm}">
<div th:replace="${inputs}"></div>
<input type="submit" value="Create">
<a th:href="@{/happyEat/shopping-lists}">Abort</a>
</form>
</div>
input.html:
<div th:fragment="create">
<input type="text" class="form-control"
placeholder=""
required
minlength="3"
maxlength="50"
id="shoppingListName"
th:field="*{name}"> // this line
<label for="shoppingListName">Name</label>
<div class="invalid-feedback">Please insert a name (at least 3 and most 50 characters).</div>
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></div> // or this line
</div>
I am not sure if this is the correct way, but it works. Change the form to:
<form th:action="@{/happyEat/shopping-lists/create}"
th:method="POST"
th:object="${__${objectForForm}__}">
and in the call hand over a String:
<div th:replace="~{fragment/form :: formWithContent(
~{fragment/shopping-list/input :: create},
'shoppingListCreateRequest)'}">
</div>