Search code examples
grailsgrails-controller

Searching the values by using dynamic finders for two fields in grails


I am trying to search using dynamic finders for two fields: status and OpenOn (a date).

render(view:'list', model:[incidentInstanceList:Incident.findAllByStatusIlikeAndOpenOnGreaterThan("closed",new Date()-7,[sort:"id",order:"desc"])]) 

The above query searches the last 7 days, but I want to search for "last week", not the last 7 days. How can I do this?


Solution

  • You may want something like this:

    def lastWeek
    use(org.codehaus.groovy.runtime.TimeCategory) {
        lastWeek = new Date() - 1.week
    }
    
    render(view:'list', model: [incidentInstanceList: Incident.findAllByStatusIlikeAndOpenOnGreaterThan( "closed", lastWeek, [sort:"id", order: "desc"])] )
    

    UPDATE:

    import java.util.Calendar
    import groovy.time.TimeCategory
    
    def roundToLastMonday(date) {
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - cal.get(Calendar.DAY_OF_WEEK) + Calendar.MONDAY)
        cal.getTime()
    }
    
    def getLastWeekRange() {
        def startDate, endDate
        use(TimeCategory) {
          startDate = roundToLastMonday(1.week.ago)
          endDate = startDate + 1.week - 1.second
        }
        [startDate, endDate]
    }
    
    def range = getLastWeekRange()
    def result = Incident.withCriteria {
        like ("status", "closed")
        between ("open", range[0], range[1])
    }
    render(view:'list', model: [incidentInstanceList: result]