在这里扩展 Asimov 的答案是一个代码示例(对于Drupal 7),它显示了用于选择节点的分类术语过滤器。选定的术语存储在会话中并在查询中用于过滤结果。
您可以将其放在自定义模块中。它不需要视图或任何其他贡献的模块。在下面的示例代码中,自定义模块的名称是tic。将tic重命名为您的自定义模块的名称。
需要四个要素:
- 输出过滤器并获取并输出结果的函数
- 过滤器形式
- 一个自定义提交函数,在会话中存储选择的过滤器选项
- 清除会话的重置功能
使用 hook_menu() 调用 tic_fetch_results()。
获取、过滤、输出结果
此示例使用动态查询,因为它很容易使用条件进行扩展。
/**
* Filters, fetches and outputs results
*/
function tic_fetch_results() {
// Adds filter form to the build array.
$form = drupal_get_form('tic_term_filter_form');
$output = drupal_render($form);
$node_types = array('article', 'page', 'blog_post');
// Sets up dynamic query
$query = db_select('node', 'n')
->extend('PagerDefault')
->limit(33)
->fields('n', array('nid', 'title'))
->condition('n.type', $node_types, 'IN')
->condition('n.status', 1);
// Fetches selected values from session and applies them to the query.
if (isset($_SESSION['form_values']['terms']) && count($_SESSION['form_values']['terms']) > 0) {
$query->join('field_data_field_tags', 'tags', 'n.nid = tags.entity_id');
$query->condition('tags.field_tags_tid', $_SESSION['form_values']['terms'], 'IN');
$query->condition('tags.bundle', $node_types, 'IN');
}
$result = $query->execute();
$items = array();
foreach ($result as $row) {
$items[] = array('data' => $row->nid . ' - ' . $row->title);
// do something interesting with the results
}
$output .= theme('item_list', array('items' => $items, 'title' => '', 'type' => 'ul', 'attributes' => array()));
$output .= theme('pager');
return $output;
}
构造表单
分类术语选项列表由词汇标签填充
/**
* Implements hook_form().
*/
function tic_term_filter_form($form, &$form_state) {
// Loads terms from the Tags vocabulary and use as select options.
$vocab = taxonomy_vocabulary_machine_name_load('tags');
$terms = taxonomy_get_tree($vocab->vid);
$term_options = array();
foreach ($terms as $term) {
$term_options[$term->tid] = $term->name;
}
// Sets the values that are stored in session as default.
$storage = (isset($_SESSION['form_values']) ? $_SESSION['form_values'] : 0);
$selected_terms = isset($storage['tags']) ? $storage['tags'] : NULL;
$form['terms'] = array(
'#title' => 'Filter by terms',
'#type' => 'select',
'#options' => $term_options,
'#multiple' => TRUE,
'#default_value' => $selected_terms,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Filter'),
);
$form['reset'] = array(
'#type' => 'submit',
'#value' => t('Reset'),
'#weight' => 30,
'#submit' => array('tic_tools_reset'),
);
return $form;
}
在会话中存储选定的值
/**
* Implements hook_form_submit().
*/
function tic_term_filter_form_submit(&$form, &$form_state) {
// Stores form values in session.
$_SESSION['form_values'] = $form_state['values'];
}
重置过滤器
/*
* Clears set filters.
*/
function tic_tools_reset() {
if (isset($_SESSION['form_values'])) {
unset($_SESSION['form_values']);
}
drupal_goto(current_path());
drupal_set_message('Filters were reset');
}