Search code examples
grailsviewcontrollergrails-orm

grails, pass data from controller to generated _form.gsp view


I got a domain class (Booking) with a User property (using SpringSecurityCore Plugin) and the corresponding views (_form, create, edit, index, show.gsp).

A normal user should not be able to set the user the normal way:

<g:select id="user" name="user.id" from="${usermanagement.User.list()}" optionKey="id" required="" value="${dailyBookingInstance?.user?.id}" class="many-to-one"/>

With this every user can select from all users in a dropdown menu. A normal user shouldnt be able to do this, it should be automatically set to the current logged in user.

For this matter I created a function in BookingController:

def currentUser() {

        User user = springSecurityService.getCurrentUser()
        log.error(user)
        [user: user]    
    }

The logging works, I got the right output in the console - But I dont know how I get this user in my _form.gsp. For all I know the user should be available in a view called currentUser.gsp but I need him in _form.gsp.

My goal is to diverge in my view between Admin and User via

<sec:ifAllGranted roles="ROLE_ADMIN">secure stuff here</sec:ifAllGranted>

and set the content of the User Dropdown menue there:

  • Admin: from="${usermanagement.User.list()}
  • normal user: from="${user} (return from currentUser() in Controller)

With this (normal user) I'm getting the error: Cannot get id from null, which means the user is not available in the view.


Solution

  • _form.gsp being a template you won't have a controller method directly for it. You have to pass the value to some real views.

    By default, the _form.gsp template is called in edit.gsp and create.gsp.

    You should be able to return the current user to your view like this:

    def edit(Booking bookingInstance){
         ...
         User user = springSecurityService.getCurrentUser()
         respond bookingInstance, model:[user:user]
    }
    

    Then use it in your _form.gsp