Search code examples
htmlspringspring-mvcenumsthymeleaf

Enum values depending on controller site in thymeleaf


My enum:

public enum ADD_OR_EDIT {

    ADD("/user/add", "addForm"), EDIT("/user/edit", "editForm");

    private String thAction;
    private String thObject;

    ADD_OR_EDIT(String thAction, String thObject) {
        this.thAction = thAction;
        this.thObject = thObject;
    }
    //getters and setters ommited to clear view
}

My controller line for edit

addAttribute("addOrEdit", ADD_OR_EDIT.EDIT);

My controller line for add:

addAttribute("addOrEdit", ADD_OR_EDIT.ADD);

The question is how to fix my thymeleaf form to get value depending on that.

For example:

   <form action="#" th:action="(@{addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${addOrEdit.thObject}"
      method="post">

(This one doesn't work)

UPDATE:

The problem is with the second parameter of enum - thObject.

in add:

model.addAttribute("basicForm", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);

in edit:

model.addAttribute("editForm", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);

Maybe the value of th:object is "addForm" instead of addForm and this cause an error.

UPDATE2:

This one works:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${basicForm})"
      method="post">

This one works also:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${editForm})"
      method="post">

So the case now is to connect them by enum like we did on thAction: This doesnt work:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${{addOrEdit.thObject})"
      method="post">

Solution

  • use th:action="${addOrEdit.thAction}" instead of th:action="@{addOrEdit.thAction}"

    update:

    model.addAttribute("form", basicForm);
    model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);
    in edit:
    
    model.addAttribute("form", editForm);
    model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);
    
    
    <form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${form}"
          method="post">