Supporting dynamic date range searches

Background

This article shows how you can define some preset date parameter values that are dynamically expanded to a date search. This allows you to search for this week or next month.

Process

The following hook_pre_process.groovy script can be used to add support for some pre-defined date searches. This provides an easy way (without calculating dates) to search for things from yesterday, last week, last 2 weeks etc.

It looks for an invented CGI parameter called 'date' and dynamically maps these to the correct date query.

Add the following code to the collection’s hook_pre_process.groovy script. The date parameter should start to work as soon as the hook script is saved.

if (transaction?.question?.inputParameterMap["date"] != null) {
  def today=new Date()
  if (transaction.question.inputParameterMap["date"] == "yesterday") {
    transaction.question.inputParameterMap["meta_d1"] = String.format('%te%tb%tY',today-2,today-2,today-2)
  }
  else if (transaction.question.inputParameterMap["date"] == "last7days") {
    transaction.question.inputParameterMap["meta_d1"] = String.format('%te%tb%tY',today-8,today-8,today-8)
  }
  else if (transaction.question.inputParameterMap["date"] == "last14days") {
    transaction.question.inputParameterMap["meta_d1"] = String.format('%te%tb%tY',today-15,today-15,today-15)
  }
  else if (transaction.question.inputParameterMap["date"] == "last31days") {
    transaction.question.inputParameterMap["meta_d1"] = String.format('%te%tb%tY',today-32,today-32,today-32)
  }
}