Overriding Play 2.1 Checkbox Form Helper for Twitter Bootstrap

混江龙づ霸主 提交于 2019-12-06 02:58:34

I had a similar problem: the checkbox were not well formatted for TwitterBootstrap CSS.

So I had to define my own checkbox helper (in order to add the <label> tag):

File path:

app\views\helper\checkbox2.scala.html

Content:

@(field: play.api.data.Field, args: (Symbol,Any)*)(implicit handler: FieldConstructor, lang: play.api.i18n.Lang)

<label class="checkbox">
    @checkbox(field, args:_*)
</label>

Then, I have redefined my fields constructor template to match Twitter Bootstrap:

File path:

app\views\helper\bootstrapInput.scala.html

Content:

@(elements: helper.FieldElements)

<div class="control-group @if(elements.hasErrors) {error}">
    <label class="control-label" for="@elements.id">@elements.label</label>
    <div class="controls">
        @elements.input
        @if(!elements.errors.isEmpty) {
            <span class="help-inline alert alert-error">@elements.errors(elements.lang).mkString(", ")</span>
        }
        <span class="help-block">@elements.infos(elements.lang).mkString(", ")</span>
    </div>
</div>

Then I have created a field constructor with an impicit call to the template above:

File path:

app\controllers\helpers\BootstrapHelper.scala

Content:

package controllers.helpers

import views.html.helper.FieldConstructor

object BootstrapHelper {
  implicit val myFields = FieldConstructor(views.html.helper.bootstrapInput.f)
}

And finally, I just import it in my "normal" views:

@import helper._
@import helpers.BootstrapHelper._

This is exactly was is written in the doc (http://www.playframework.com/documentation/2.1.0/ScalaFormHelpers) and it works out finely.

At the end, all my inputs were correctly displayed with the Twitter Bootstrap and the checkbox as well.

Hope this helps

EDIT as asked by Mike Slinn, I just added files path and a few details about the implicit call of the field constructor. However, the file names do not really matter here and variants are possible to make the implicit call (see the doc).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!