views_handler_sort_date.inc

  1. 3.x handlers/views_handler_sort_date.inc
  2. 2.x handlers/views_handler_sort_date.inc

File

handlers/views_handler_sort_date.inc
View source
  1. <?php
  2. /**
  3. * Basic sort handler for dates.
  4. *
  5. * This handler enables granularity, which is the ability to make dates
  6. * equivalent based upon nearness.
  7. *
  8. * @ingroup views_sort_handlers
  9. */
  10. class views_handler_sort_date extends views_handler_sort {
  11. function option_definition() {
  12. $options = parent::option_definition();
  13. $options['granularity'] = array('default' => 'second');
  14. return $options;
  15. }
  16. function options_form(&$form, &$form_state) {
  17. parent::options_form($form, $form_state);
  18. $form['granularity'] = array(
  19. '#type' => 'radios',
  20. '#title' => t('Granularity'),
  21. '#options' => array(
  22. 'second' => t('Second'),
  23. 'minute' => t('Minute'),
  24. 'hour' => t('Hour'),
  25. 'day' => t('Day'),
  26. 'month' => t('Month'),
  27. 'year' => t('Year'),
  28. ),
  29. '#description' => t('The granularity is the smallest unit to use when determining whether two dates are the same; for example, if the granularity is "Year" then all dates in 1999, regardless of when they fall in 1999, will be considered the same date.'),
  30. '#default_value' => $this->options['granularity'],
  31. );
  32. }
  33. /**
  34. * Called to add the sort to a query.
  35. */
  36. function query() {
  37. $this->ensure_my_table();
  38. switch ($this->options['granularity']) {
  39. case 'second':
  40. default:
  41. $this->query->add_orderby($this->table_alias, $this->real_field, $this->options['order']);
  42. return;
  43. case 'minute':
  44. $formula = views_date_sql_format('YmdHi', "$this->table_alias.$this->real_field");
  45. break;
  46. case 'hour':
  47. $formula = views_date_sql_format('YmdH', "$this->table_alias.$this->real_field");
  48. break;
  49. case 'day':
  50. $formula = views_date_sql_format('Ymd', "$this->table_alias.$this->real_field");
  51. break;
  52. case 'month':
  53. $formula = views_date_sql_format('Ym', "$this->table_alias.$this->real_field");
  54. break;
  55. case 'year':
  56. $formula = views_date_sql_format('Y', "$this->table_alias.$this->real_field");
  57. break;
  58. }
  59. // Add the field.
  60. $this->query->add_orderby(NULL, $formula, $this->options['order'], $this->table_alias . '_' . $this->field . '_' . $this->options['granularity']);
  61. }
  62. }