gabriel
gabriel

Reputation: 447

Grails - controller access variables from gsp

I have the following grails controller

class UserController {

    def userService
    def roleService

    def index() { 
        def roles = roleService.listRoles()
        [roles: roles]
    }

    def userDetails() {
        [user: userService.getUser(params.id), role:params.role]
    }

    def updateUser() {
        def user = userService.getUser(params.id)
        if (!(params.username)) {
            flash.message = "You have to enter a username!"
            redirect(action: "userDetails")
        }
        else {
            user.username = params.username
            user.person.title = params.title
            user.person.given = params.given
            user.person.middle = params.middle
            user.person.family = params.family
            userService.updateUser(user)
            redirect(action: "index")
        }
    }
}

Starting with index() the user gets a list of all roles and users currently available. The user may then select one particular user being linked to the userDetails()-action. There I retrieve the information about the id of the user with params.id and the user's role name with params.role.

In userDetails.gsp the user is able to update some of the user's properties. However, if he doesn't enter a username, he should be redirected back to the userDetails.gsp. (I know that I could check this with the required-attribute within the gsp - it's just to understand the functionality)

And here is where I get stuck - when using the userDetails()-action, two parameters are passed to the gsp. But now when committing the redirect I don't know how to access this information. As a result, rendering the userDetails.gsp results in an error as the required information concerning the user and the role are not available.

Any help would be highly appreciated!

Upvotes: 0

Views: 1200

Answers (1)

Dónal
Dónal

Reputation: 187399

You should change the form (presumably) that submits to the updateUser action, so that it also sends in the role. Then if the data submitted is invalid, you simply include these parameters when redirecting back to the userDetails action.

def updateUser() {

    def user = userService.getUser(params.id)

    // I'm not sure if this the right way to get a Role from the role parameter
    // but presumably you can figure that out yourself
    def role = roleService.getRole(params.role)

    if (!(params.username)) {
        flash.message = "You have to enter a username!"
        redirect action: "userDetails", params: [id: params.id, role: params.role]
    }
}

As an aside, the way you're manually binding each parameter to the user object is unnecessarily verbose. Grails' databinding can do this automatically.

Upvotes: 1

Related Questions