Tag Archives: Grails

Grails link with additional parameters

As I have said before, I love how easy it is to create links in Grails. However, when I was starting out I could never remember the syntax when I needed more information on the URL than just the ID.

Lets say I have a UrlMapping (grails-app/conf/UrlMapping.groovy) of:

"/player/photos/$id?/matchReport/$matchReportId?" {
     controller = "player"
     action = "photos"
 }

I always had problems remembering how to get the matchReportId onto the URL. As with so many things in Grails it turns out to be very simple; use the params parameter:

<g:link controller="player" action="photos" id="${matchPlayer.player.id}" params="[matchReportId:matchPlayer.matchReport.id]">

and good ol’ Grails is smart enough to build the URL like

rfw/player/photos/6/matchReport/26

Accessing Grails Config from a Grails Service

Grails configuration, particularly environment specific, information is kept in grails-app/conf/Config.groovy.

Access to this information is very easy in the presentation layer (controllers, gsp) using:

def imagesDir = grailsApplication.config.uploadDir

You can use this same mechanism from within a service; you just have to inject the grailsApplication into the service

class NewsService {
     def grailsApplication
     ...
     def imagesDir = grailsApplication.config.uploadDir

If you get an error message similar to the following, then the grailsApplication has  not been injected:

groovy.lang.MissingPropertyException: No such property: grailsApplication for class: NewsService

Creating a link in a Grails Service

I love how easy it is to create a link in Grails but often I want to use this same mechanism to create a link in a Service. For example, I have a service that sends out a News Report to a list of subscribers. There a links in the generated email back to the website.

Creating a link in a service turns out to be quite simple. I found this work around at http://jira.codehaus.org/browse/GRAILS-2605.

def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib()
 def visitUs = g.createLink(controller: 'site', action: 'index', absolute: 'true')
 def manageSubscriptions = g.createLink(controller: 'comm', action: 'index', absolute: 'true')

The absolute: ‘true’ is really important as I am embedded these links in an email.

Grails URLMapping

Given this URLMapping

"/news/show/$id?/item/$itemId?" {
 controller = "news"
 action = "show"
 }

results in the following params:

URL: http://localhost:8080/rfw/news/show
params: [“action”:”show”, “controller”:”news”]

URL: http://localhost:8080/rfw/news/show/1
params: [“id”:”1″, “action”:”show”, “controller”:”news”]

URL: http://localhost:8080/rfw/news/show/1/item
params: [“id”:”1″, “action”:”show”, “controller”:”news”]

URL: http://localhost:8080/rfw/news/show/1/item/4
params: [“id”:”1″, “action”:”show”, “controller”:”news”, “itemId”:”4″]