Reputation: 569
I have a user with multiple roles, I want to display his available roles in a dropdown in the header. One way is to write my own custom tag, but is there anyother easy way to do that.
Upvotes: 1
Views: 1237
Reputation: 35894
Here is how I do it. Somewhere, have this method available.
def getRoleMap(userInstance) {
List roles = Role.list()
roles.sort { r1, r2 ->
r1.authority <=> r2.authority
}
Set userRoleNames = []
if (userInstance.id) {
for (role in userInstance.authorities) {
userRoleNames << role.authority
}
}
LinkedHashMap<Role, Boolean> roleMap = [:]
for (role in roles) {
roleMap[(role)] = userRoleNames.contains(role.authority)
}
return roleMap
}
Then call this method and forward it on to the view as [roleMap:roleMap]
Your view looks like this..
<div class='role-map' style="width: 300px; height: 200px; overflow:auto;border: 1px solid black">
<g:each in="${roleMap}">
<div>
<g:checkBox name="userRoles" value="${it.key.authority}" checked="${it.value}"/>
${it.key.authority.encodeAsHTML()}
</div>
</g:each>
</div>
Then when a user is saved, you can do the following:
UserRole.removeAll(user)
params.userRoles.roleAuthorities.each { roleAuthority ->
UserRole.create(user, Role.findByAuthority(roleAuthority))
}
Upvotes: 0
Reputation: 120406
You could create a custom tag library:
class RolesTagLib {
static namespace = 'my'
def springSecurityService
def currentUserRoleSelect = { attrs ->
def user = springSecurityService.getCurrentUser()
def roles = UserRole.findAllByUser(user).collect { it.role } as Set
attrs.from = roles
attrs.optionKey = attrs.optionKey ?: 'id'
attrs.optionValue = attrs.optionValue ?: 'authority'
out << g.select(attrs)
}
}
And then in your GSP:
<my:currentUserRoleSelect name="role"/>
Upvotes: 3
Reputation: 1843
You can use the <g:select>
tag, using from="${yourPrincipal.roles}
and setting a property to be displayed. More in the official docs: http://grails.org/doc/latest/ref/Tags/select.html
Upvotes: 0