nIx..
nIx..

Reputation: 370

Grails: can we pass string as id in g:link? Or any other way?

Scenario:
I want to create g:link which will redirect to

www.xyz.com/controller/action/title_of_question

instead

www.xyz.com/controller/action/id_of_question

I know that later one can be created easily configuring id param of the g:link.
Please note that title_of_question is String separated with hyphen (-)
Can anybody suggest me how to achieve it?

Upvotes: 1

Views: 731

Answers (3)

Paweł Piecyk
Paweł Piecyk

Reputation: 2789

Short answer: yes, we can :)

If you have no rule in UrlMappings.groovy which defines id as Long or Integer you can create links with String identifier like below:

<g:link controller="controllerName" action="show" id="someName">Link!</g:link>

And define controllers action with identifier as String:

def show(String id) {
    ...
}

Upvotes: 1

Tegi
Tegi

Reputation: 778

I would suggest doing the following:

def someAction() {
    if(params.id.matches(/[0-9]+/)) {
        //logic for id of question
    } else {
        //you could check if it is separated with dashes
        //logic for title of question
    }
}

This would trigger the id logic:

www.xyz.com/controller/someAction/15 

And this the 'title' logic:

www.xyz.com/controller/someAction/title-of-question

Upvotes: 1

dustin
dustin

Reputation: 101

I think the best thing to do is create a new Action in your controller that takes your ID, and redirects your to the URL you are trying to goto.

<g:link resource="book" action="name" id="${id}">New Book</g:link>

then in your controller.

def name(int id) {
    //take the ID, get the name, and redirect to the proper .gsp.
}

Upvotes: 1

Related Questions