Search code examples
grailsgroovygrails-plugin

Property date must be a valid Date error, when using jquery UI plugin


I have a tasks class, which has a date field. In my view file, I have this line of code :

<g:textField name="date" value="${tasksInstance?.date}" id="datePicker" />

And using the jquery ui plugin, I added this code to my <head> tag :

<g:javascript>
$(document).ready(function()
{
$("#datePicker").datepicker({dateFormat: 'mm/dd/yy'});
})
</g:javascript>

But when I save the date field, I get the following error:

Property date must be a valid Date error

Edit:

Tasks.groovy

package mnm.schedule

class Tasks {
    static belongsTo = [ user : User, project: Project ]
        String reason
        boolean completed
        String title
        String description 
                Date date
        static constraints = {
            user(nullable:false)
            completed(nullable:true)
            title(nullable:false)
            description(size:1..500,nullable:false)
                reason(nullable:true)
        }
        String toString(){
                this.title
        }
}

And controller action code is :

def save() {
        def adminProject = params.managersProject
        def foundProject = Project.findByNameLike("$adminProject")
        def tasksInstance = new Tasks(params)
        foundProject.addToTasks(tasksInstance)
        if (!tasksInstance.save(flush: true)) {
            render(view: "create", model: [tasksInstance: tasksInstance])
            return
        }
        redirect(action: "show", id: tasksInstance.id)
    }

How to recover from this?


Solution

  • I assume you're getting a String like '02/16/2012'? You could just call:

    params.date = Date.parse( 'MM/dd/yyyy', params.date )
    

    Before creating the Task object...

    There's probably an automatic way of doing this in Grails as well using PropertyEditorSupport


    Edit

    Also, in grails 2.0, you can do:

    def date = params.date( 'myVar', 'MM/dd/yyyy' )
    

    To parse the date param out of the params object