CodeMed
CodeMed

Reputation: 9205

setting a date in spring mvc application

In a spring mvc application that utilizes hibernate and jpa, I have a form in a spring mvc application that needs to store the current date in a field in the row that gets created in the underlying data table when the form is submitted. I have the model, controller, and jsp all set up, but when it runs I get a system.out.println() telling me that the failure is localized to the creation date not being generated. How can I change my code below so that the creation date gets generated and sent where it needs to go?

It looks like maybe the jquery datepicker function is not working in this code. But I am not really sure. A fresh viewpoint would help.

Here is my jsp:

<script>
    $(function () {
        $("#created").datepicker({ dateFormat: 'yy/mm/dd'});
    });
</script>
<div class="container">
    <jsp:include page="../fragments/bodyHeader.jsp"/>
    <c:choose>
        <c:when test="${document['new']}">
            <c:set var="method" value="post"/>
        </c:when>
        <c:otherwise>
            <c:set var="method" value="put"/>
        </c:otherwise>
    </c:choose>

    <h2>
        <c:if test="${document['new']}">New </c:if>
        Document
    </h2>

    <form:form modelAttribute="document" method="${method}"
               class="form-horizontal">
        <div class="control-group" id="patient">
            <label class="control-label">Patient </label>

            <c:out value="${document.patient.firstName} ${document.patient.lastName}"/>
        </div>
        <myapp:inputField label="Name" name="name"/>
        <myapp:inputField label="Description" name="description"/>
        <div class="control-group">
            <myapp:selectField name="type" label="Type " names="${types}" size="5"/>
        </div>
        <td><input type="file" name="file" id="file"></input></td>
        <div class="form-actions">
            <c:choose>
                <c:when test="${document['new']}">
                    <button type="submit">Add Document</button>
                </c:when>
                <c:otherwise>
                    <button type="submit">Update Document</button>
                </c:otherwise>
            </c:choose>
        </div>
    </form:form>
    <c:if test="${!document['new']}">
    </c:if>
    <jsp:include page="../fragments/footer.jsp"/>
</div>
</body>  

Here are the relevant parts of the controller:

@RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.GET)
public String initCreationForm(@PathVariable("patientId") int patientId, Map<String, Object> model) {
    Patient patient = this.clinicService.findPatientById(patientId);
    Document document = new Document();
    patient.addDocument(document);
    model.put("document", document);
    return "documents/createOrUpdateDocumentForm";
}

@RequestMapping(value = "/patients/{patientId}/documents/new", method = RequestMethod.POST)
public String processCreationForm(@ModelAttribute("document") Document document, BindingResult result, SessionStatus status) {
    new DocumentValidator().validate(document, result);
    if (result.hasErrors()) {
        //THIS IS BEING RETURNED BECAUSE DocumentValidator.validate() INDICATES THAT THERE IS NO created DATE  
        return "documents/createOrUpdateDocumentForm";
    }
    else {
        this.clinicService.saveDocument(document);
        status.setComplete();
        return "redirect:/patients?patientID={patientId}";
    }
}

Here is the DocumentValidator class, which is called by the above controller:

public class DocumentValidator {

    public void validate(Document document, Errors errors) {
        String name = document.getName();
        // name validaation
        if (!StringUtils.hasLength(name)) {
        System.out.println("--------------------- No Name --------------------------");
        errors.rejectValue("name", "required", "required");
        }
        else if (document.isNew() && document.getPatient().getDocument(name, true) != null) {
        System.out.println("--------------------- Name Already Exists --------------------------");
        errors.rejectValue("name", "duplicate", "already exists");
        }
        // type valication
        if (document.isNew() && document.getType() == null) {
        System.out.println("--------------------- No Type --------------------------");
        errors.rejectValue("type", "required", "required");
        }
     // type valication
        if (document.getCreated()==null) {
            //THIS LINE IS BEING PRINTED BECAUSE created HAS NOT BEEN POPULATED WITH A VALUE
        System.out.println("--------------------- No Created Date --------------------------");
        errors.rejectValue("created", "required", "required");
        }
    }

}

And here are the relevant parts of the model, which are parts of Document.java:

@Column(name = "created")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(pattern = "yyyy/MM/dd")
private DateTime created;

public void setCreated(DateTime created) {this.created = created;}
public DateTime getCreated() {return this.created;}

The above code compiles, but when the user presses the submit button after entering the information to upload a document, the eclipse console prints out the line from DocumentValidator indicating that the date field created does not exist.

Upvotes: 1

Views: 1707

Answers (2)

Ashish Jagtap
Ashish Jagtap

Reputation: 2819

Where you bind datePicker control to input type element in your code

 $("#created").datepicker({ dateFormat: 'yy/mm/dd'});

according to this you bind datepicker control to element having Id="created" attribute, I don't see any element having Id="created" in your jsp file

you should have to map your datePicker control to some input element as

<form:input path="created" id="created" class="date-pick" readonly="true" />

hope this will solve your problem

Upvotes: 1

storm_buster
storm_buster

Reputation: 7568

There is no <input name='created'> in your form

Upvotes: 0

Related Questions