Как мне динамически генерировать эту таблицу в форме? - PullRequest
0 голосов
/ 13 июня 2019

Я передаю атрибут в модель и проверяю, чтобы он не был нулевым ...

Контроллер:

@GetMapping(Mappings.MAIN) // AliasFor @RequestMapping(method = RequestMethod.GET)
    public String getMainView(Model model,
                              @ModelAttribute(AttributeNames.VIEW_RECIPE) ViewRecipe recipe){

        log.info(recipe.toString());

        if(recipe==null){
            recipe = new ViewRecipe();
            recipe.setIngredientList(new ArrayList<>());

        }
        model.addAttribute(AttributeNames.VIEW_RECIPE, recipe);


        return ViewNames.MAIN_VIEW;
    }

Утилиты:

public class ViewNames {
    public static final String HOME = "home";

public class AttributeNames { 
    public static final String VIEW_RECIPE="view-recipe";

public class Mappings {
    public static final String HOME ="home";

Шаблон Thymeleaf:

<form id="get-recalculated-recipe" action="#" method="post">
    <table>
        <tr><th>Quantity</th>
            <th>Unit</th>
            <th>Ingredient Name</th>
            <th>Multiplier</th>

        </tr>
        <tr th:each="ing : ${view-recipe.ingredientList}">
            <td>
            <input type="text" th:field="*{ing.quantity}"/>
            </td>
            <td>
                <input type="text" th:field="*{ing.unit}"/>
            </td>
            <td>
                <input type="text" th:field="*{ing.ingredientName}"/>
            </td>
            <td>
                <input type="text" th:field="*{ing.ingredientName}"/>
            </td>
        </tr>
    </table>
</form>

1 Ответ

1 голос
/ 17 июня 2019

Прежде всего, вы не уверены, что список ингредиентов не равен нулю.Подумайте о случае, когда вы вызываете свой контроллер, и рецепт не равен нулю, но атрибут рецепта содержит список ингредиентов.Он будет отправлен как ноль на ваш взгляд.Вы можете изменить его, например, на:

if(recipe==null){
        recipe = new ViewRecipe();
        recipe.setIngredientList(new ArrayList<>());
}else if(recipe.getIngredientList() == null){
        recipe.setIngredientList(new ArrayList<>());
}
model.addAttribute(AttributeNames.VIEW_RECIPE, recipe);

Во-вторых, вы используете выражения выбора (*{...}) в своих полях th: это хорошо, но вам нужно, чтобы в вашей команде был определен объект команды.формировать тоже и ссылаться на него из входов.Вы можете сделать это, добавив объект команды в форму следующим образом:

<form id="get-recalculated-recipe" th:object="${view-recipe}" action="#" method="post">

и изменив поля th: для ссылки на него с помощью итератора, чтобы входная информация передавалась при публикации формы.Также добавив th: значение, чтобы фактически получить текущее значение атрибутов при загрузке страницы:

<tr th:each="ing, iter : ${view-recipe.ingredientList}">
    <td>
    <input type="text" th:value="${ing.quantity}" th:field="*{ingredientList[__${iter.index}__].quantity}"/>
    </td>
    <td>
        <input type="text" th:value="${ing.unit}" th:field="*{ingredientList[__${iter.index}__].unit}"/>
    </td>
    <td>
        <input type="text" th:value="${ing.ingredientName}" th:field="*{ingredientList[__${iter.index}__].ingredientName}"/>
    </td>
</tr>

Я предлагаю вам взглянуть на https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html, это поможет вам в будущем.

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