grailsgspgrails-controllercommand-objects

Grails use Command Object and object in the same gsp


I have a controller, edit method paint the user info in the form file. But when I try to update with errors the command object return userCommand object so I lost all info from user object.

Is there any way to use both in the same form? or what I'm missing here.

UserController class

class UserController {
    def edit(User user) {
        respond user
    }
    def update(UserCommand userCommand) {
        log.debug "Update a User"

        if (userCommand.hasErrors()) {
            respond userCommand.errors, view: 'edit'
            return
        }
     }
}

_form.gsp file

<g:form action="update">
    <div class="form-group">
        <label for="firstName">User First Name</label>
        <input class="form-control" name="firstName" value="${user?.firstName}">
    </div>

    <div class="form-group">
        <label for="lastName">User Last Name</label>
        <input class="form-control" name="lastName" value="${user?.lastName}">
    </div>
</g:form>

when call edit method, I get the user info

Update with errors, I got lost the user info


Solution

  • Thank you @tuomas-valtonen. You drive me to find the solution.

    def edit(User user) {
            UserCommand userCommand = new UserCommand()
            bindData(userCommand, user)
            respond userCommand
        }