Mark Chorley
Mark Chorley

Reputation: 2107

Spring form control bound to LocalDate defaults to now

I have three select controls (day, month and year) for Date Of Birth bound using Spring form:select to an org.joda.time.LocalDate.

As Date Of Birth is optional, I would like it if the date could be empty by default. However Date Of Birth is initialised with today's date. This happens even if I set the Date Of Birth to null in the model.

This means that today's date will be sent as the value of that field when the form is submitted, which is not what I want. I am not too concerned about how the date is stored in the database as long as the null representation is clear (although null would be preferable to something like 0000-00-00 00:00:00 of course) .

How can I work around this problem? I could write a wrapper for LocalDate which has a default value of null and only initialises the LocalDate when the setters are called by the form binding perhaps. It seems like a fairly common problem so perhaps there is a better way.

Upvotes: 2

Views: 690

Answers (1)

Mark Chorley
Mark Chorley

Reputation: 2107

I have found a partial way around this problem, but I confess I don't understand why it works. Moving the controls into a JSP tag has helped. This shows no selected date on first page view. If the user enters a date and submits, that is shown on page refresh.

However when the form is submitted with the selects empty, the value of the hidden input to which the three selects are linked using a datepicker (which is bound to today's date), is submitted, which is not desirable. It would be ideal if the hidden input were not populated as well, but I think wrapping LocalDate with an object that initialises the date fields as null or empty strings is the only way to achieve that. This is the code which shows the day as not selected on first page load.

<spring:bind path="${path}.dayOfMonth">
  <select>
       <option value="0"></option>
       <c:forEach items="${days}" var="day">
         <option value="${day}"<c:if test="${date.dayOfMonth eq day}"> selected="selected"</c:if>>${day}</option>
       </c:forEach>
  </select>
</spring:bind>
-- month and year dropdowns
<form:input path="${datepickerPath}" cssStyle="display:none;" />

Upvotes: 1

Related Questions