I’d like to set it so when a user visits the application with a telephone number in the URL Grails directs the user to the specified profile, for example:
localhost:8080/Application/profile/07871216969 -> /user/show/User.findByUserTelephone(07871216969)
or preferably
localhost:8080/Application/07871216969 -> /user/show/User.findByUserTelephone(07871216969)
However, I have no idea how to reference the telephone number in the URL when calling the findByUserTelephone closure; I’ve noticed something like:
/profile/$telephoneNumber however I’m not entirely sure how that works out.
Also, as the /user/show action requires an id in the parameters I am not sure if the findUserByTelephone closure is any use as it returns the User as an object, and I can’t seem to either getId() or .id the object to retrieve the id.
SOLVED/SOLUTION:
I solved this by creating another action in the Controller called profile, this action then had code similar to the following:
def profile = {
if(User.findByUserTelephone(params.userTelephone)) {
def userInstance = User.findByUserTelephone(params.userTelephone)
if (!userInstance) {
flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
redirect(action: "list")
}
else {
[userInstance: userInstance]
}
} else {
render("Sorry, that user wasn't found in our database.")
}
}
I then created the following UrlMapping entry:
`"/$userTelephone"(controller: "user", action: "profile")`
Thus, when a user enters a telephone number into the system (or any string after the /) it will route the user to the user/profile action, which will attempt to find a user by their telephone number. If successful, will show the users details otherwise will show an error message.
It will probably save you some headaches later if you use a url path which is not the same as a controller name. So if you have something like:
you won’t have any URL patterns that match multiple URLMapping entries which can get a little confusing. I would guess that just:
would work, but I would expect to end up in situations where Grails gets confused by multiple URLMappings matching the same request path unless you’re very careful.