Dan
Dan

Reputation: 1000

Display date object/value from controller to view in Play Framework/Scala

I have a date from a model that is retrieved by the controller and displayed in the view. However, the date does not display as a value in the field in the view.

Here is the view:

@(intakeForm: Form[Application.IntakeAdd], lookups: java.util.List[Lookup], users: java.util.List[User], intake: Intake)

@main(null) {
...
<div class="element-date">
  <label class="title"><span class="required">*</span>Date Requested:</label>
    <div class="item-cont">
    <input class="large" data-format="yyyy-mm-dd" type="date" name="daterequested" required="required" placeholder="Date" value="@intake.daterequested" />
    <span class="icon-place"></span>
    </div>
</div>

...
}

I have the field value as:

value="@intake.daterequested"

but it does not display any value -- all other values work, just not the date.

The value is stored as a Java Date() object in the model:

@Constraints.Required
@Formats.DateTime(pattern = "yyyy-MM-dd")
public Date daterequested;

I am guessing there may be some translation I could use in the view to correct this?

I appreciate the help!

Upvotes: 1

Views: 1216

Answers (1)

Steve Chaloner
Steve Chaloner

Reputation: 8202

Check what the date is rendered as by displaying it directly in the HTML, e.g. <span>@intake.daterequested</span>

I suspect it will be in the format dow mon dd hh:mm:ss zzz yyyy (see the javadoc for Date#toString) which does not match the required format of yyyy-mm-dd.

You can either use a SimpleDateFormat in your template to format the date as required, or else create a DTO for Intake that already contains the date in the required format. If you choose the former, change your code to have the following:

value="@(new SimpleDateFormat("yyyy-MM-dd").format(intake.daterequested))"

You can also define reusable date format for the template. If you have to format multiple dates, it will save creating a formatter for each.

For example...

The controller

package controllers;

import java.util.Date;
import play.mvc.*;

import views.html.*;

public class HomeController extends Controller {
    public Result index() {
        return ok(index.render(new Date()));
    }
}

The template This demonstrates using an in-line format and a reusable format.

@import java.text.SimpleDateFormat
@(date: java.util.Date)

<html>
    @defining(new SimpleDateFormat("yyyy-MM-dd")) { dateFormatter =>
        <body>
            <div>
                <b>Raw: </b>@date
            </div>
            <div>
                <b>In-line formatter: </b>@(new SimpleDateFormat("yyyy-MM-dd").format(date))
            </div>
            <div>
                <b>Shared formatter: </b>@dateFormatter.format(date)
            </div>
        </body>
    }
</html>

The output

Raw: Wed Dec 14 09:36:15 CET 2016

In-line formatter: 2016-12-14

Shared formatter: 2016-12-14

Upvotes: 2

Related Questions