Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Order and sort items with tabledrag

By editor , 8 March, 2022
Question

How to order elements with draggable table ?

Draggable table Form Example


Step 1 : Form build

$group_class = 'group-order-weight';
$items = [
  1 => ['id' => 1, 'label' => 'L1', 'weight' => 1],
  2 => ['id' => 2, 'label' => 'L2', 'weight' => 2],
  3 => ['id' => 3, 'label' => 'L3', 'weight' => 3],
];
// Build table.
$form['items'] = [
  '#type' => 'table',
  '#caption' => $this->t('Items'),
  '#header' => [
    $this->t('Label'),
    $this->t('ID'),
    $this->t('Weight'),
  ],
  '#empty' => $this->t('No items.'),
  '#tableselect' => FALSE,
  '#tabledrag' => [
    [
      'action' => 'order',
      'relationship' => 'sibling',
      'group' => $group_class,
    ]
  ]
];
// Build rows.
foreach ($items as $key => $value) {
  $form['items'][$key]['#attributes']['class'][] = 'draggable';
  $form['items'][$key]['#weight'] = $value['weight'];
  // Label col.
  $form['items'][$key]['label'] = [
    '#plain_text' => $value['label'],
  ];
  // ID col.
  $form['items'][$key]['id'] = [
    '#plain_text' => $value['id'], //@todo add field
  ];
  // Weight col.
  $form['items'][$key]['weight'] = [
    '#type' => 'weight',
    '#title' => $this->t('Weight for @title', ['@title' => $value['label']]),
    '#title_display' => 'invisible',
    '#default_value' => $value['weight'],
    '#attributes' => ['class' => [$group_class]],
  ];
}

Stem 2 : Form submit

$items = $form_state->getValue('items');

 

 

Tags

  • Drupal 8
  • Code
  • Drupal 9
  • Table
Create HTML Table. render and theming

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer