Search code examples
grailsgspgrails-domain-class

Grails, change domain class property from gsp


what's the method used to change a domain classes property within the gsp?

Ex:

a domain class project has a dueDate which is of type date. I want to within the gsp, set its date without using the tag The reason is, I'm using jquery's datepicker which is nice since instead of having an ugly dropdown for mm/dd/yyyy it has a nice little calendar for one to click on. Anywho, any ideas?

Thanks in advance :D :D :D


Solution

  • Well, Grails uses a MVC pattern and therefore you should not directly change a domain class property within a GSP page.

    Of course you can use the JQuery date picker but you should provide a controller action to update your domain class property

    def updateDateUsingAjax() {
      def domain = MyDomain.load(params.id)
    
      /*
      Lets pretend the content of params.date has the format MM/dd/yyyy  
      You can use Date.parse method of the Groovy JDK to create a java.util.Date instance of a String. 
      http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#parse(java.lang.String, java.lang.String)
      */
    
      domain.myDate = Date.parse('MM/dd/yyyy', params.date)
    
      domain.save()
    }
    

    Now all you have to write is an Ajax call to this controller action and you successfully separated the presentation layer from the rest of your application.

    And here is how your GSP could look like.

    <!doctype html>
    <html>
    <head>
        <meta name="layout" content="main"/>
        <title>Welcome to Grails</title>
        <r:require module="jquery-ui"/>
    </head>
    <body>
    <div>
        <g:formRemote name="myForm" url="[controller: 'standard', action: 'updateDateUsingAjax']" onSuccess="showDialog()">
            <p>Your date: <g:textField name="pick"/> </p>
            <p><g:hiddenField name="id" value="your id"/></p>
            <input type="submit" value="Delete Book!" />
        </g:formRemote>
    
    </div>
    
    <div id="dialog" title="Success" style="display:none;">
        <p>You have successfully updated your date</p>
    </div>
    
    <script type="text/javascript">
        $(document).ready(function()
        {
            $("#pick").datepicker({dateFormat: 'yy/mm/dd'});
        })
    
        function showDialog() {
            $("#dialog").dialog();
        }
    </script>
    </body>