Spring Boot + Thymeleaf: как создать метод формы + контроллера для сложной сущности на одной странице - PullRequest
0 голосов
/ 26 марта 2020

Учитывая простую сущность, скажите это:

@NoArgsConstructor
@EqualsAndHashCode(of="uuid")
@Getter
@Setter
public class StrengthUnit implements Serializable 
{
    private static final long serialVersionUID = -5093332492793962831L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String uuid = UUID.randomUUID().toString();

    @Size(min = 1, max = 50, message = "The name must be between 1 and 50 characters long!")
    @Column(nullable = false, length = 50)
    private String name;

    public StrengthUnit(String name) 
    {
        this.name = name;
    }

    @Override
    public String toString()
    {
        return name;
    }
}

Очень простая форма Thymeleaf, скажите это:

<!-- Form -->
                <form action="#" th:action="@{/strengthUnits/save}" th:object="${strengthUnit}" method="post">

                    <!-- Hidden ID -->
                    <div class="form-group" hidden="true">
                        <label for="id" class="formFieldTitle">ID</label>
                        <input type="text" class="form-control" id="id" placeholder="Some UUID" th:field="*{id}">
                        <label class="errorMessage" th:if="${#fields.hasErrors('id')}" th:errors="*{id}">ID Error</label>
                    </div>

                    <!-- Name -->
                    <div class="form-group">
                        <label for="name" class="formFieldTitle">Name</label><span class="requiredField"> (Required)</span>
                        <input type="text" class="form-control" id="name" placeholder="Name" th:field="*{name}"
                            th:classappend="${validated == true ? (#fields.hasErrors('name') ? 'is-invalid' : 'is-valid') : ''}"
                            th:attr="readonly=${#authorization.expression('!hasAuthority(''Edit Strength Units'')')}">
                        <label class="errorMessage" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</label>
                    </div>

                    <button sec:authorize="hasAuthority('Edit Strength Units')" type="submit" class="btn btn-primary">Save</button>
                    <a sec:authorize="hasAuthority('Edit Strength Units')" class="btn btn-secondary" th:href="@{'/strengthUnits/'}">Cancel</a>
                    <a sec:authorize="!hasAuthority('Edit Strength Units')" class="btn btn-secondary" th:href="@{'/strengthUnits/'}">Back</a>
                </form>

И связанный метод контроллера:

@PostMapping("/save")
public String save(@Valid StrengthUnit strengthUnit, BindingResult result, Model model)
{
    if (result.hasErrors())
    {
        model.addAttribute("validated", true);

        return "forms/strengthUnitForm";
    }

    try
    {
        strengthUnitService.save(strengthUnit);
    }
    catch (PersistenceException | DataIntegrityViolationException ex)
    {
        result.addError(new FieldError("strengthUnit", ExceptionUtils.getColumnName(ex), ExceptionUtils.getErroneousValue(ex), 
            false, null, null, "This value already exists!"));

        return "forms/strengthUnitForm";
    }

    return "redirect:/strengthUnits/";
}

Что если я добавлю свойство этого типа List<AnotherEntity> в этот класс StrengthUnit? Как изменить форму, чтобы позволить пользователю каким-либо образом редактировать список другой сущности в этой же форме, не покидая страницу?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...