Search code examples
scalaplayframework-2.0nested-formsstrip

Play 2.0 Nested forms: generate <input id="email"> instead of <input id="user_email">


Posted this to Play user group; I account for the sole view, so hoping to get a view, or perhaps even an answer ;-)

Nested forms are great, but there's one glitch that adds boilerplate to either javascript or scala templates.

For example, given:

@inputText(field = _form("user.email"),
    '_label-> "Email Address*",
    'class-> "required email",
    'placeholder-> "[email protected]"
)

the generated input field is something like:

<input id="user_email" name="user.email" ...>

Now, when you want to validate the email address client-side you then have to reference DOM id: $('#user_email')

Where $('#email') would be more natural.

I know I can set the id attrib manually in the template but would prefer to, by default, have the nested name (user in this case) stripped out from the id attrib.

Looking in github views helper directory, I am not finding where I can get access to the generated id (i.e. which file I need to overload and how).

Anyone know how to pull this off and/or have a better approach?


Solution

  • Here is where the field's ID is auto-generated:

    https://github.com/playframework/Play20/blob/master/framework/src/play/src/main/scala/play/api/data/Form.scala#L274

    There's not really any way you can override that behaviour, but you could write your own @inputText helper that strips the "user_" part from the ID when generating the HTML.

    Basically copy-paste the default helper and replace

    <input type="text" id="@id" ...
    

    with your own code, e.g.

    <input type="text" id="@processFieldId(id)" ...
    

    or (untested!):

    <input type="text" id="@(id.split('_').last)" ...
    

    Then just import your custom helper in your template, and use it just like you would use @inputText.