Search code examples
formsgrailsurl-mappingurlmappings.groovy

UrlMappings and Forms - how do they work?


UrlMappings are a great feature for links, but do they also work for forms?

Suppose we have a mapping like this:

"/map/$a" {
    controller="form"
    action="show"
}

a <g:link controller="form" action="show" params="[a:'test'] /> will now be rewritten as <a href="/appname/map/test" />

But a form like this:

<g:form controller="form" action="show">
   <g:textField name="a" />
</g:form>

will not have the same effect. It will result in requesting /appname/form/show?a=whatever

I know that a form can't be rewritten at HTML-creation time like a link - mainly because the value of the parameter is not known at this time, but I hoped that this URL would be redirected to the "nice" URL.

Is there a way to do stuff like that in grails? Or do I have to write my own redirect?


Solution

  • I guess I've found the answer:

    URL-Rewriting seems only to work at the time when the HTML gets rendered. So

    <g:form controller="form" action="show" params="[a:'test']">
       <g:textField name="b" />
    </g:form>
    

    will result in /appname/map/test. But that's not what I want - I want the URL to be rewritten when the form gets submitted.

    So I came up with a redirect action:

    class FormController {
    
        def index() { }
        def show() {
            render("yep"+params.a)
        }
        def submit() {
            redirect(controller:'form',action:'show',params:params)
        }
    }
    

    and I rewrite my form as

    <g:form controller="form" action="submit">
       <g:textField name="a" />
    </g:form>
    

    This seems to work great (at the cost of one redirect)