Search code examples
drupaldrag-and-dropthemessections

How to create a drag and drop table with sections in same way as block admin page?


How to make a drupal table with multiple sections that has support for drag and drop?

It should be similar to drupal block admin page:

block admin page .

I have only found examples on how to do it with on section.


Solution

  • There is a nice article, in which you may get an answer but you may find the following guide more useful.

    1. You may create the table with the ability to change wight. This is a sample of constructor:

    function mymodule_form_weights() {
      $data = array(
        array('id' => 1, 'title' => 'Lorem ipsum dolor sit amet', 'active' => 0, 'weight' => -10),
        array('id' => 2, 'title' => 'Consectetuer adipiscing elit', 'active' => 1, 'weight' => -7),
        array('id' => 3, 'title' => 'Ut wisi enim ad minim veniam', 'active' => 1, 'weight' => 0),
        array('id' => 4, 'title' => 'Quis nostrud exerci tation', 'active' => 0, 'weight' => 5),
        array('id' => 5, 'title' => 'Ullamcorper suscipit lobortis', 'active' => 0, 'weight' => 3),
      );
      $form['#tree'] = true;
      foreach($data as $row) {
        $form['table'][$row['id']]['title'] = array(
          '#value' => $row['title'],
        );
        $form['table'][$row['id']]['active'] = array(
          '#value' => $row['active'] ? 'yes' : 'no',
        );
        $form['table'][$row['id']]['weight'] = array(
          '#type' => 'weight',
          '#default_value' => $row['weight'],
        );
      }
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'save',
      );
      return $form;
    }

    1. Themization

    function theme_mymodule_form_weights($form) {
      $rows = array();
      foreach(element_children($form['table']) as $id) {
        $form['table'][$id]['weight']['#attributes'] = array('class' => 'weight');
        $rows[$id]['class'] = 'draggable';
    
        foreach(element_children($form['table'][$id]) as $name) {
          $rows[$id]['data'][] = drupal_render($form['table'][$id][$name]);
        }
      }
    
      drupal_add_tabledrag('weights-form', 'order', 'sibling', 'weight');
    
      $output = theme('table', array('Title', 'Active', 'Weight'), $rows, array('id' => 'weights-form'));
      $output. = drupal_render($form);
    
      return $output;
    }
    3. hook_theme()

    function mymodule_theme() {
      return array(
        'mymodule_form_weights' => array('arguments' => array('form' => null)),
      );
    }

    Don't forget that it is php, not js as in snippet.