How to add default values to input fields in Thymeleaf

33,016

Solution 1

Solved the problem by removing th:field altogether and instead using th:value to store the default value, and html name and id for the model's field. So name and id is acting like th:field.

Solution 2

I'm slightly confused, you're adding currentUser and a new'd user object to the model map.

But, if currentUser is the target object, you'd just do:

<input type="text" name="firstname" value="James" th:value="${currentUser.firstname}" />

From the documentation: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

Share:
33,016
Kingamere
Author by

Kingamere

Updated on July 09, 2022

Comments

  • Kingamere
    Kingamere almost 2 years

    I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.

    Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.

    This should behave just like a standard "edit profile" page.

    Here is a segment of my edit_profile.html page:

    First Name:

    Here is the view controller method that returns edit_profile.html page:

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
        public String getEditProfilePage(Model model) {
            model.addAttribute("currentUser", currentUser);
            System.out.println("current user firstname: " + currentUser.getFirstname());
            model.addAttribute("user", new User());
            return "edit_profile";
        }
    

    currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.

    Thanks.

  • Kingamere
    Kingamere almost 9 years
    No, I want to display the current information of the object "currentUser". Once the new fields are entered, they are stored in "user", and the "user" object is sent as a PUT request to update the fields.
  • dardo
    dardo almost 9 years
    Then you're trying to tie two different states to one field, only way I can see that being done is through some javascript trickery.
  • Babu
    Babu almost 7 years
    for other focus the difference is that the attribute name is added