Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to input in Play 2 custom FieldConstructor

I am making a custom field constructor in Play 2:

@(elements : helper.FieldElements)

<div class="@if(elements.hasErrors) {error}">
    <label for="@elements.id">@elements.label</label>
    <div class="input">
        @elements.input
        <span class="errors">@elements.errors.mkString(", ")</span>
        <span class="help">@elements.infos.mkString(", ")</span>
    </div>
</div>

I need the input element to always have a particular class "my-class". How can I do this? The FieldElements class has an args member. I tried making a copy of the elements with " my-class" appended to the value associated with '_class in args, but this did not seem to affect the input element.

like image 429
mushroom Avatar asked Dec 04 '13 00:12

mushroom


1 Answers

One way for custom input in Play Framework is

@(elements: helper.FieldElements)
<div class="form-group @elements.args.get('_class) @if(elements.hasErrors) {has-error}" id="@elements.args.get('_id).getOrElse(elements.id + "_field")">

    @if(elements.hasName) {
        <label class="control-label" for="@elements.id">@elements.name</label>
    } else {
        <label class="control-label" for="@elements.id">@elements.label(elements.lang)</label>
    }

    @if(elements.input.toString().contains("class=")) {

        @Html(elements.input.toString().replaceFirst("(class=[\"'])", "$1form-control "))

    } else {

        @Html(elements.input.toString().replaceFirst("(<\\w+ )", "$1class=\"form-control\" "))

    }


    @elements.errors.map { error =>
        <p class="help-block">@error</p>
    }

    @elements.infos.map { info =>
        <span class="help-block">@info</span>
    }
</div>
like image 114
Nguyễn Hồng Phúc Avatar answered Sep 21 '22 18:09

Nguyễn Hồng Phúc