Thymeleaf: Как правильно указать имя HTML и атрибут Id в случае вложенного объекта List? - PullRequest
2 голосов
/ 23 сентября 2019

Сущность содержит вложенные списки.С th: each я могу видеть значения, отображаемые в форме, но в базе данных не сохраняется никаких обновлений, и я уверен, что это из-за неправильных атрибутов 'name' и / или 'id', которые Thymeleaf не транскодирует.Как мне их указать?

Я пробовал с другим сочетанием имени и идентификатора и следовал документации, но ни один из них не работал.Пробовал только с th: каждой переменной цикла, но это тоже не сработало.

Основной объект: CustomAttributesMap.java

@Entity
public class CustomAttributesMap implements Serializable {

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

    private EntityType entityType;

    @ElementCollection
    //@ManyToMany
    private List<CustomAttributesFieldMap> customAttributesFieldMapList = new ArrayList<>();
// setter and getter code
...
}

Первый дочерний список: CustomAttributesFieldMap.java

@Entity
public class CustomAttributesFieldMap implements Serializable {

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

    private CustomFieldType fieldType;

    @ElementCollection
    //@ManyToMany
    private List<CustomAttribute> customAttributesList = new ArrayList<>();
// setter and getter methods.
...
}

Второй дочерний список:

@Entity
public class CustomAttribute implements Serializable {

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

    private String name;
    private boolean required;
    private String value;
// setter and getter methods
....
}

Controller.java

...
@ModelAttribute("customAttributesMapList")
    public List<CustomAttributesMap> populateCustomAttributes() {
       return customerAttributeMapService.findAll();
    }


@PostMapping("/customAttributeCustomization")
    public String saveCustomAttributeCustomization(
        List<CustomAttributesMap> customAttributesMapList, Model model) {
        Logger.getLogger(WebController.class, "Logigng for WebController").error(""
                + "customAttributesMapList " + customAttributesMapList);
        for(CustomAttributesMap customAttributesMap: customAttributesMapList) {
            customerAttributeMapService.save(customAttributesMap);
        }
....

CustomAttributesEdit.html

<form class="user" th:action="@{/customAttributeCustomization}" th:object="${customAttributesMapList}" method="POST">
..
<div class="card p-3 collapse" style="max-width: 50rem;" th:each="customAttributesMap, iterIndex: ${customAttributesMapList}" th:id="${customAttributesMap.entityType}">
..
<div th:each="customAttributeFieldMap, iterStat : ${customAttributesMap.customAttributesFieldMapList}">
...
<table align="left" id="alphaTable" class="table table-sm table-bordered">
<thead>
<tr class="d-flex" id="theadRow">
<th class="col-7 text-center" >Name</th>
<th class="col-3 text-center" >Mandatory</th>
<th class="col-2 text-center">Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="customAttribute, rowStat : ${customAttributeFieldMap.customAttributesList}" class="d-flex" th:id="rowalpha-+${rowStat.index}">
<td class="col-7">
<input class="form-control"  type="text" th:value="${customAttribute.name}"  th:id="customAttributesMapList+${iterIndex.index}+.customAttributesFieldMapList+${iterStat.index}+.customAttributesList+${rowStat.index}+.name" name="customAttributesMapList[+${iterIndex.index}+].customAttributesFieldMapList[+${iterStat.index}+].customAttributesList[+${rowStat.index}+].name"/> 

</td>
....
</table>
</form>

Я ожидаю, что в приведенной выше форме значение customattribute.name необходимо отредактировать и сохранить в базе данных, котораяВ настоящее время не происходит.После отладки на контроллере основной список сущностей (CustomAttributesMapList) не изменяется и не содержит никаких пользовательских обновлений в HTML-форме.Конечно, это связано с тем, что приведенный выше код с неправильным именем и идентификатором для поля ввода не может быть правильным.

Обновление Хорошо, я не смог найти никакого полезного ответа, поэтому я сгладилу сущностей должна быть одна сущность CustomAttrubute, которая имеет свойства entityType и fieldType и имеет CustomAttributesMap (список), который содержит сущность CustomAttribute, и эта карта будет объектом формы, отправляемым во внешний интерфейс из веб-контроллера.Но я хотел бы проверить, есть ли у кого-нибудь ответ на головоломку Thymeleaf :).

1 Ответ

0 голосов
/ 23 сентября 2019

Используйте @RequestMapping вместо @ PostMapping

    @RequestMapping(value = "/customAttributeCustomization",method=RequestMethod.POST)
    public String saveCustomAttributeCustomization(
        List<CustomAttributesMap> customAttributesMapList, Model model) {
        Logger.getLogger(WebController.class, "Logigng for WebController").error(""
                + "customAttributesMapList " + customAttributesMapList);
        for(CustomAttributesMap customAttributesMap: customAttributesMapList) {
            customerAttributeMapService.save(customAttributesMap);
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...