Grails use Command Object and object in the same gsp

236 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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

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

You should use UserCommand on both actions parameter and create your User object inside the action from UserCommand by data binding. This is to separate your View Model from the actual Model.

Like other users stated, return the whole UserCommand instead of UserCommand.errors. You can access UserCommand.errors in the view also.

Remember, that after your UserCommand is valid, you still need to create User and validate it and return any errors it has. Both can be run through <g:renderErrors bean="${user}"> for example.