Drupal 7: Tabledrag (Drag & Drop)

Autor: Sven am Tue, 27.11.2012 - 15:00

Drupal verfügt über ein tolles Feature namens "Tabledrag" um Menüeinträge schnell per Drag and Drop sortieren zu können. Diese Funktionalität ist auch für Custom Module sehr geeignet. Hier ein kleines Tutorial wie sich so etwas realisieren lässt.

Für Drupal 6 ist hier ein mit Links.

/**
 * Implements hook_form().
 */
function example_sort_form($form, &$form_state) {
  $form = array();
  $form['sort'] = array('#tree' => TRUE);
  $order = 0;

  $results = db_select('custom_table', 'c')->fields('c')->orderBy('weight', 'ASC')->execute();
  foreach($results as $result) {
    $form['sort'][$result->id]['#sort'] = (object) array(
      'id' => $result->id,
      'title' => $result->title,
      'weight' => $order,
    );

    $form['sort'][$result->id]['#weight'] = $order;
    $form['sort'][$result->id]['weight'] = array(
      '#type' => 'textfield',
      '#title' => t('Weight for @title', array('@title' => $result->title)),
      '#title_display' => 'invisible',
      '#size' => 4,
      '#default_value' => $order,
      '#attributes' => array('class' => array('weight')),
    );

    $order++;
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

/**
 * Implements hook_theme()
 */
function example_sort_theme() {
  return array(
    'example_sort_form' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Theme the form
 */
function theme_example_sort_form($vars) {
  $form = $vars['form'];
  $output = '';
  $header = array(t('Title'), t('Weight'));
  $rows = array();
  foreach (element_children($form['sort']) as $id) {
    $row = array();
    $row[] = t('@title', array('@title' => $form['sort'][$id]['#sort']->title));
    $row[] = drupal_render($form['sort'][$id]['weight']);
    $rows[] = array('data' => $row, 'class' => array('draggable'));
  }
  drupal_add_tabledrag('sort', 'order', 'sibling', 'weight');
  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => 'sort'),
  ));
  $output .= drupal_render_children($form);
  return $output;
}

/**
 * Implements hook_form_submit().
 */
function example_sort_form_submit($form, &$form_state) {
  foreach ($form_state['values']['sort'] as $id => $values) {
    db_update('custom_table')->fields(array('weight' => $values['weight']))->condition('id', $id)->execute();
  }

  drupal_set_message(t('The settings have been updated.'));
}

Fragen/Anregungen bitte in den Kommentaren