Drupal中的暴露日期过滤器 - 使“月”可选

时间:2013-05-05 16:38:20

标签: drupal-7 drupal-views

我的网站上有一个视图,其中列出了视频存档和具有年/月粒度的公开过滤器。我的问题是过滤器只接受选择年和月值的输入,但我真的需要让用户按年过滤而不必选择月份,也可以先选择年份然后如果需要,可以按月过滤来优化搜索。

我是Drupal的初学者,所以我对Drupal的基础设施了解不多。我甚至不知道存储视图的位置。如果我这样做,也许我可以以某种方式改变代码。

1 个答案:

答案 0 :(得分:3)

我不确定是否有内置方法使月份可选或不可用,但这可能是一种解决方法。您可以添加两个公开的过滤器,一个具有Year粒度,另一个具有Year-Month粒度。然后你可以使用hook_form_FORM_ID_alter来改变暴露的形式(确保添加条件以检查它是你的视图并显示id)。您可以添加验证回调,以便在提交表单时,如果选择了月份,则可以在year_month字段中设置年份。

我没有测试过这个,但这通常是我接近form_alter的方式。

<?php
function my_module_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];
  if ($view->name == 'my_view' && $view->current_display == 'my_display') {
    // Assuming the year exposed filter is 'year' and year-month exposed filter
    // is 'year_month'.
    $form['year_month']['value']['year']['#access'] = FALSE; // Hides the year
    $form['#validate'][] = 'my_module_my_view_filter_validate';
  }
}

function my_module_my_view_filter_validate($form, &$form_state) {
  $values = isset($form_state['values']) ? $form_state['values'] : array();
  // When the month is set, grab the year from the year exposed filter.
  if (isset($values['year_month']['value']['month'])) {
    // If the year is not set, we have set a user warning.
    if (!isset($values['year']['value']['year'])) {
      drupal_set_message(t('Please select a year.'), 'warning');
    }
    else {
      // Otherwise set the year in the year_month filter to the one from our
      // year filter.
      $year = $values['year']['value']['year'];
      $form_state['values']['year_month']['value']['year'] = $year;
    }
  }
}
?>
相关问题