Play Framework - @helper custom @input text field

May 8, 2017

Target

<![CDATA[ <div class="form-group”> <label class="text-left col-lg-5 col-sm-6 control-label”>Emailadres contactpersoon</label> <div class="col-lg-7 col-sm-6”> <input maxlength="50” placeholder="Emailadres” tabindex="4”  class="form-control” id="Emailadres” name="Emailadres” type="text”> </div> </div> ]]>
SyntaxHighlighter.highlight();

Solution

Render the input text without the labels part of the play framework defaults by creating a file customfield.scala.html under app/view/helper:
<![CDATA[ @(elements: helper.FieldElements) @elements.input <span class="errors”>@elements.errors.mkString(", “)</span> <span class="help”>@elements.infos.mkString(", “)</span ]]>
SyntaxHighlighter.highlight();
Create a custom input text consctructor by adding a new file under app/view/helper:
<![CDATA[ @** * Generate an HTML input text. * * Example: * {{{ * @inputText(field = myForm(“name”), args = ‘size -> 10, ‘placeholder -> “Your name”) * }}} * * @param field The form field. * @param args Set of extra attributes. * @param handler The field constructor. *@ @(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: FieldConstructor) @inputType = @{ args.toMap.get(‘type).map(_.toString).getOrElse(“text”) } @input(field, args.filter(_._1 != ‘type):_*) { (id, name, value, htmlArgs) => <label class='text-left col-lg-5 col-sm-6 control-label’>@htmlArgs.toMap.get(‘label)</label> <div class="col-lg-7 col-sm-6”> <input type=”@inputType” id=”@id” name=”@name” value=”@value” @htmlArgs.toMap.get(‘args)/> </div> } ]]>
SyntaxHighlighter.highlight();
Add the following to your templates
<![CDATA[ @import helper._ @implicitField = @{ FieldConstructor(helper.customField.f) } ]]>
SyntaxHighlighter.highlight();
Last, call the custom constructor via:
<![CDATA[ @helper.retailerRegisterInputText( field = registerRetailerForm(“retailer_name”), ‘label -> “Bedrijfsnaam”, ‘placeholder -> “Bedrijfsnaam”, ‘args -> “maxlength=50 tabindex=1 class=form-control placeholder=Bedrijfsnaam “, ‘_showConstraints -> false ) ]]>
SyntaxHighlighter.highlight();