1

I have a field called birthday that is defined for users. In views, is there any way to create a filter that filters only by month? Smallest values it lets me select is year and month where I only need month. (to find users who are born in April for example). Thanks for any help.

enter image description here

1

If you are using the date module, then you can set the granularity to month in the date filter settings.

Then, you can configure the filter like so Operator: "is equal to" and Date: "this month".

If you don't see these filter settings, you would have to enable the date_views module.

  • I have set the granularity to only month, but on the configure screen, it forces me to select a year too. See the screen shot please. – farjam Apr 4 '16 at 16:08
  • @farjam You need to change the select a date (from your screenshot) to Enter a relative date. Then enter a relative date in the relative date field. e.g. this month, eighth month etc. See php.net/manual/en/datetime.formats.relative.php – Vergil K Apr 4 '16 at 16:25
  • Thanks for the help, but in the actual filter that produces (when I set it to exposed), it defaults to current month, but still shows year too. My goal is for an admin to go to that view, select a month, and be able to view all users who were born in that month. He can then switch to another month and view users born in the other month. – farjam Apr 4 '16 at 16:56
  • 1
    @farjam In that case these links below may help you display only month in the exposed filter: link1 link2 – Vergil K Apr 4 '16 at 17:52
1

Here is what I ended up doing:

/**
 * Impliments hook_form_views_exposed_form_alter
 *
 * Used to change exposed date filter to month only, as this is not available in the views UI
 */
function MODULENAME_form_views_exposed_form_alter(&$form, $form_state) {
  if( $form['#id'] == 'form_id') {
    // Switch date formatter to month only
    $form['field_date']['value']['#date_format'] = 'm';
    // Add extra validator to handle filter submit
    $form['#validate'][] = 'MODULENAME_views_exposed_form_validate';
  }
}
/**
 * Custom validator for exposed date filter
 */
function MODULENAME_views_exposed_form_validate(&$form, &$form_state) {
  $handlers = &$form_state['view']->filter;
  foreach ($handlers as $key => $handler) {
    if (!empty($handler->options['exposed'])
     && isset($form[$key]['value']['#type'])
     && $form[$key]['value']['#type'] == 'date_select'
     && $form[$key]['value']['#date_format'] == 'm'){
      $handler->options['granularity'] = 'month';
      $handler->format = 'm';
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.