开发者

Drupal: how to show a form (select) acting as filter options, then show a table of stuff from the database?

开发者 https://www.devze.com 2023-01-23 16:16 出处:网络
I want a simple filter form, and a table below it. When the user changes the option on the select form, the table automaticaly changes. I think thats done with ahah.

I want a simple filter form, and a table below it. When the user changes the option on the select form, the table automaticaly changes. I think thats done with ahah.

I want this (some things can change, like the fieldset containing the table, and other stuff):

Drupal: how to show a form (select) acting as filter options, then show a table of stuff from the database?

But working.. of course..

I'm currently showing that page using one function. It's a complete mess and something like "NEVER DO THIS", but i'm researching and trying some stuff as i'm a drupal learner. This is the relevant code:

    form = array();  
    ahah_helper_register($form, $form_state);  
    //query here, build $options for the select

$form['listar_veics'] = array(  
        '#type'   => 'fieldset',  
    '#prefix' => '<div id="listar-veics-wrapper">',   
    '#suffix' => '</div>',  
    '#tree'   => TRUE,
    );

if (!isset($form_state['values']['listar_veics']['filial']))
    $choice = 1;
else 
    $choice = $form_state['values']['listar_veics']['filial'];


$form['listar_veics']['filial'] = array(
    '#type' => 'select', 
    '#title' => "Listar veículos da filial", 
    '#options' => $filiais,
    '#default_value' => $choice,
    '#ahah' => array(
        'event'     => 'change',
        'path'      => ahah_helper_path(array('listar_veics')),
        'wrapper'   => 'listar-veics-wrapper',
        'method'    => 'replace',
        ),
);

//query for the rows i wanna show

//building $data array, the rows array

//building $header, as an array of strings

$table = theme_table($header, $data);

$page = drupal_render($form);
$page .= $table;
return $page;

So in this code, drupal will only replace the form itself, when i change the option on the select, it shows the new value on the select, but the table isnt rendered a开发者_Go百科gain thus not changing.

Thanks, apreciate every suggestion.


I recommend looking at the views module.

http://drupal.org/project/views

With that installed, you can create a custom query.

  1. Add all the fields that you would like displayed on your table. (Placa, Marca)
  2. Then add any filters that you would like to limit your query by. (Listar veiculos da filial)
  3. When adding the filter you "expose" it so that when looking at the query, you can change the options on the page.
  4. Then if you want to view what you just made, you need to add a display. If you make it a page display, you can set the path directly to the table.

For more information might I recommend http://gotdrupal.com/videos/drupal-views-tutorial.

If you want neater exposed fields I might also recommend http://drupal.org/project/better_exposed_filters


To expand Asimov's answer here is a code example (for Drupal 7) that shows a taxonomy term filter for selecting nodes. The selected terms are stored in the session and used in the query to filter the results.

You can put it in a custom module. It doesnt require Views or any other contributed modules. In the example code below the name of the custom module is tic . Rename tic to the name of your custom module.

Four elements are needed:

  1. A function that outputs the filter and fetches and outputs the results
  2. The filter form
  3. A custom submit function that stores the chosen filter options in the session
  4. A reset function that clears the session

Use hook_menu() to call tic_fetch_results().

Fetch, filter, output results

This example uses a dynamic query because it is easy to extend with conditions.

/**
 * 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;
}

Construct the form

The taxonomy terms options list is populated from the Vocabulary tags

/**
 * 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;
}

Store selected values in the session

/**
 * Implements hook_form_submit().
 */
function tic_term_filter_form_submit(&$form, &$form_state) {

  // Stores form values in session.
  $_SESSION['form_values'] = $form_state['values'];
}

Reset the filter

/*
 * 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');
}


The following page on the drupal forum contains a very clear explanation of the drupal form process and what to do in your specific case. See the answer from user Jaypan.

http://drupal.org/node/1770512

To sum his answer up:

  1. Create a submit button on the form to submit the chosen filter. This button has it's own submit function:

    $form['submit_filter'] = array( '#type' => 'submit', '#value' => 'Apply the filter', '#submit' => array('apply_filter') );

  2. Create the submit function for applying your filter. In this function store the value of the filter to save it for the next form building when the page refreshes. Also set $form_state['rebuild'] to TRUE.

    function apply_filter($form, &$form_state) { // Save the filter $form_state['filter'] = $form_state['values']['filter']; $form_state['rebuild'] = TRUE; }

Now you will have access to the filter value the next time the form is built. Just check for the existence of the value like:

if (isset($form_state['filter']))
{
   // do your filtering here
}

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消