Wednesday, November 19, 2008

Great little Grails Gem

Hi All

I have not blogged for ages. Been really busy trying to get a large retail web site live for the x-mas. Any way here is little gem i found.

I need to have a drop down list of accounts a user has access to. This needs to show on every page so they can quickly change accounts. Now there are many way i could do this in grails but i thought a tag lib would fit quite well.

So basically i want a drop down select list but i want to transparently get the list of accounts from info in the session. So i figure all i have do is wrap the existing grails select taglib. Grails allows you to call existing tags from within a controller or in my case another taglib. So i simply call the grails select tag with the correct parameters and send it to the out stream.

Here is the tag lib.

class GlobalCommonTagLib {


def accountListSelect = {attrs,body ->


User user = User.get(session.userId)


def accountList = user.accountAccesses.collect {it.account};
attrs.from = accountList

attrs.optionKey = 'id'

attrs.optionValue = 'name'

out << g.select(attrs)


}

}


Then in my GSP


<g:accountListSelect id="acountId" name="id"/>




So easy i am writing this blog with the time i saved.
Enjoy :)

1 comment:

Ted Naleid said...

You just saved me a bunch of time, thanks!


I had everything right but was missing the "out <<" before the call to "g.foo(attrs)" so the string was going out into the ether. I knew it was calling the other taglib, but couldn't figure out where the output is going.

I had thought that it'd wire up the out in the taglib that I was calling instead of returning a string, but apparently not :).