开发者

Grails <g:select> woes

I am using the Spring Security Plugin. By default this plugin has created three classes in my project.

org.me.example.UserRole.UserRole org.me.example.UserRole.User org.me.example.UserRole.Role

The User and Role classes are unaware of each other, but the UserRole class has both a User and a Role object. The Role object has only one attribute, a string called authority.

My objective is to obtain all Users with a certain authority in a <g:select> statement.

Here is one of my attempts:

<g:select name="loggedBy.id" from="${org.me.example.UserRole.UserRole.list(fetch:[(role.authority):"ROLE_ADMIN"])}" optionKey="id" value=""  />

I do realize that this would return a UserRole list and not a User list. Is there anyway to "join" my开发者_开发技巧 classes so I can retrieve the data I want? Looking for the cleanest solution.

Update:

I think there was some confusion about what my classes look like, so here are the stripped down versions.


class UserRole {

    User user
    Role role

    //more stuff

}

class Role {

    String authority

    //more stuff

}

class User {

    //lots of stuff, but nothing that links back to the Role class or the UserRole class

}

Crudof's answer worked for me after some alterations. Crudof pointed out that the package name UserRole does not follow Java package naming conventions. This is true, but if I remember right the Spring Security Core plugin automatically creates that package and the classes in it, so I didn't mess with the name... But it has been a while since I did that, so I could be mistaken about it automatically naming the package.

<g:set var="desiredRole" value='${org.me.example.UserRole.Role.findByAuthority("ROLE_ADMIN")}' />
<g:select name="loggedBy.id" from="${org.me.example.UserRole.UserRole.findAllByRole(desiredRole).user}" optionKey="id" value=""  />


  1. Your package names are not conform to common java-standards: package names should/HAVE TO start with lower case character. Otherwise one is confused, that it might be a class (where UserRole is a nested class of UserRole).
  2. Basically your code snippet is fine (concept-wise). Note, that you cannot use double-quotes in double-quotes attribute values! I think this has stopped your progress. You can try the following:

    <g:set var="desiredRole" 
        value='${org.me.example.UserRole.findByAuthority("ROLE_ADMIN")}' />
    
    <g:select name="userSelect" 
        from="${org.me.example.UserRole.findAllByRole(desiredRole).user}" />
    

    Note that accessing the user-instances from the UserRole-instances is a groovy-sugar. See http://groovy.codehaus.org/Collections for a few examples.


It would be better to do this in a controller:

def usersWithAdminRole = UserRole.withCriteria {
  eq("role", Role.findByAuthority('ROLE_ADMIN'))
}.collect {
  it.user
}

<g:select from="${usersWithAdminRole}" name="loggedBy.id" optionKey="id" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜