@ModelAttribute возвращает нулевые значения с помощью thymeleaf - PullRequest
0 голосов
/ 21 декабря 2018

После нескольких дней исследований у меня возникли проблемы с поиском решения для моих методов контроллера.У меня есть два метода контроллера, которые кажутся проблематичными.Метод экономии - сохранение нулевых значений.Я понятия не имею, как привязать значения, которые вводятся в поле, к списку / всем.Один для создания значений с полями ввода, а другой для сохранения входных значений и обновления списка / всего.Я хочу получить значения, которые я поместил в поля формы, и получить обновленный список / все с новыми значениями.Обратите внимание, что я только пытаюсь сохранить два из одиннадцати атрибутов всего класса.Класс имеет двойные значения и true / false.Они сохраняются в БД, за исключением важных строковых значений.Заранее благодарим за помощь!

Первый метод:

@GetMapping("/create")
    public String showCreateForm(Model model, Branch branch) {
        List<Branch> branches = new ArrayList<>();
        BranchCreationDto branchesForm = new BranchCreationDto(branches);

        for (int i = 1; i <= 1; i++) {
            // the input field
            branchesForm.addBranch(new Branch());
        }

        model.addAttribute("form", branchesForm);
        return "branches/create";
    }

Этот метод имеет одно поле ввода, в котором можно установить значения параметра Branch.

Второй метод:

@PostMapping("/saving")
public String saveBranches(@ModelAttribute BranchCreationDto form, Model   model, Branch branch) {

    // saves null but needs to be saving the values that are being typed into the field
    this.branchRepository.saveAll(form.getBranches());

    model.addAttribute("branches", branchRepository.findAll());

    return "redirect:/all";

}

Кажется, что этот метод имеет проблему в

this.branchRepository.saveAll (form.getBranches ());

Возвращает нулевые значения.Я уже пытался положить в параметр branch.getName (), branch.getType ().Это не работает.

С помощью метода / вся программа возвращает список.

@GetMapping("/all")
public String showAll(Model model) {
    model.addAttribute("branches", branchRepository.findAll());
    return "branches/all";
}

Это мой класс-оболочка

    import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;


public class BranchCreationDto {

@Autowired
private List<Branch> branches;

    public BranchCreationDto(List<Branch> branches) {
        this.branches = branches;

    }

    public BranchCreationDto() {

    }

    public void addBranch(Branch branch) {
        this.branches.add(branch);
    }

    public List<Branch> getBranches() {
        return branches;
    }

    public void setBranches(List<Branch> branches) {
      this.branches = branches;
    }

}

И этоформа

<body>

<!-- Save -->
<form action="#" th:action="@{saving}" th:object="${form}"
    method="post">
    <fieldset>
        <input type="submit" id="submitButton" th:value="Save"> <input
            type="reset" id="resetButton" name="reset" th:value="Reset" />
        <table>
            <thead>
                <tr>
                    <th>Branch</th>
                    <th>Type</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="branch, itemStat : *{branches}">
                    <td><input th:field="*{branches[__${itemStat.index}__].branch}" /></td>
                    <td><input th:field="*{branches[__${itemStat.index}__].type}" /></td>
                </tr>
            </tbody>
        </table>
    </fieldset>
</form>

1 Ответ

0 голосов
/ 24 декабря 2018

Вы делаете неправильно, значение таким образом не передается от контроллера к листу тимьяна. Я приведу один пример.Пример:

 Controller:
     Model and View model =new Model and View();


            model .put ("branches", branch Repository.find All());
    return model;

Thyme leaf:
<input  id="branches" type="hidden" t h:value="${branches}" />

Теперь ваше значение передается в ветви ID.

...