Skip to content

hook_civicrm_relativeDate

Summary

Allows extensions to define custom relative date filters by returning an array with from and to date values, enabling flexible filtering beyond the built-in formats.

If your filter is just adding a longer interval to an existing filter you may not need the hook. See Adding New Filters in the user guide.

Definition

hook_civicrm_relativeDate($filter)

Parameters

  • string $filter the relative date filter that have been added to the option group relative_date_filters

Returns

  • array An associative array with from and to keys representing the start and end dates.

Examples

Here is a simple example, assuming your extension is called myextension and that the values ccourse and pcourse have been added to the option group relative_date_filters:

/**
 * Implements hook_civicrm_relativeDate().
 *
 * Allows extensions to define custom relative date filters by returning a date range.
 *
 * @param string $filter
 *   The relative date filter have been added to the option group `relative_date_filters`
 */
function myextension_civicrm_relativeDate($filter) {
  $dates = [];
  $today = new DateTime();
  $currentMonth = (int)$today->format('n');

  $courseStartYear = ($currentMonth >= 9) ? (int)$today->format('Y') : (int)$today->format('Y') - 1;

  if ($filter == 'ccourse') {
    $startYear = $courseStartYear;
    $endYear = $courseStartYear + 1;

    $dates['from'] = (new DateTime("{$startYear}-09-01"))->format('Ymd');
    $dates['to'] = (new DateTime("{$endYear}-08-31"))->format('Ymd');
  }

  if ($filter == 'pcourse') {
    $startYear = $courseStartYear - 1;
    $endYear = $courseStartYear;

    $dates['from'] = (new DateTime("{$startYear}-09-01"))->format('Ymd');
    $dates['to'] = (new DateTime("{$endYear}-08-31"))->format('Ymd');
  }

  return $dates;
}