Adding HTML attributes to an input component when using a custom field constructor
java, playframework, playframework-2.0, playframework-2.1
Solution
It's already built in and will work with your custom field constructors. It's actually documented under the Rendering an <input> element on the page you linked to.
Note: All extra parameters will be added to the generated HTML, except for ones whose name starts with the _ character. Arguments starting with an underscore are reserved for field constructor argument (which we will see later).
So doing something like this:
@inputText(
myForm("user"),
'_label -> "User",
'size -> 30,
'placeholder -> "User Name"
)
Will output HTML like this:
<input id="user" name="user" size="30" placeholder="User Name">
It's documented somewhere, but if you want to do `data` attributes then you have to do this:
@inputText(
...
Symbol("data-some-attribute") -> "value"
)
Problem
I am following the official Java Form Helpers documentation to write my own field constructor. I have also drawn upon the `computer-database` sample application included with Play. The template for the input control included in the `computer-database` sample application looks like this: ``` <div class="clearfix @if(elements.hasErrors) {error}"> <label for="@elements.id">@elements.label</label> <div class="input"> @elements.input <span class="help-inline">@elements.infos.mkString(", ")</span> </div> </div> ``` From this example, it's obvious how to add additional elements around the `<input>` element. My problem is that I want to alter part of the `<input ...>` element itself. I can't see how to do this because `@elements.input` renders the complete `<input type="..." value="..." ...>` HTML element, and so I have no opportunity to add additional attributes to the `input` element. What I want to do is add `placeholder="my placeholder text"`. I want to get the placeholder text from `elements.args`. I have been able to achieve what I want by doing string manipulation on the `@elements.input.buffer`, like so: ``` @(elements: helper.FieldElements) @{ val buffer = elements.input.buffer; val index = buffer.lastIndexOf(">"); // find the closing '>' buffer.delete(index, buffer.length - 1); // delete it buffer ++= " placeholder=\"" // insert the placeholder attribute buffer ++= elements.args('placeholder).toString buffer ++= "\">" // close the input tag Html(buffer.toString) // render as HTML } ``` My question though is: is there a simpler way? It there a facility for this already built into Play? Or is this my only avenue for adjusting the `input` field itself?