Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play 2.0 Framework - Custom Form Field

Thanks in advance for the time and help!

I'm trying to build a custom form field in Play 2.0.4 that uses the twitter bootstrap datepicker found here.

Basically, I'm trying to create a custom field constructor that outputs this:

<div class="input-append date error" id="expires_field" data-date="" data-date-format="mm/dd/yyyy">
    <label for="expires_field">Expiration Date</label>
    <div class="input">
        <input class="span2" size="16" type="text" name="expires" id="expires" value="mm/dd/yyyy">
        <span class="add-on"><i class="icon-th"></i></span>
        <span class="help-inline"></span>
    </div>
</div>

But, despite a lot of browsing around the internet - I've been unable how to create a custom form field in Play 2.0 where I can still validate and display errors.

I think, mostly, I'm a little confused about where the files need to be in the app structure.

Any help would be GREATLY appreciated!

Pixelworlds

like image 706
pixelworlds Avatar asked Dec 04 '12 18:12

pixelworlds


1 Answers

I've been also struggling with this and here's what I came up with:

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

@import play.api.i18n._
@import views.html.helper._

@elements = @{ new FieldElements(field.id, field, null, args.toMap, lang) }

<div class="control-group">
  <label class="control-label" for="@field.name">@elements.args.get('_label)</label>
  <div class="controls">
    <div class="input-append date" id="@field.id-picker" data-date="@field.value" data-date-format="@elements.args.get('format).getOrElse("mm/dd/yyyy")">
      <input type="text" name="@field.name" id="@field.id">
      <span class="add-on"><i class="icon-calendar"></i></span>
      <span class="help-inline">@elements.errors(elements.lang).mkString(", ")</span>
      <span class="help-block">@elements.infos(elements.lang).mkString(", ")</span> 
    </div>
  </div>
</div>

Save this in a file calendar.scala.html and use it like:

@views.html.forms.calendar(
  myform("end"),
  '_showConstraints -> false,
  '_label -> Messages("label.end.date"),
  'format -> "dd/mm/yyyy"
)

Then in your JS:

$('#end-picker').datepicker({
  weekStart: 1
}).on('changeDate', function(ev){
  $('#end-picker').datepicker('hide');
});

The name of the id is generated with field.name + "-picker"

Also, you could use an inputText:

@inputText(
  myform("start"),
  '_showConstraints -> false,
  '_label -> Messages("label.start.date"),
  'class -> "date-picker",
  Symbol("data-date-format") -> "mm/dd/yyyy"
)

Hope it helps

like image 109
Eldelshell Avatar answered Oct 20 '22 22:10

Eldelshell