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');
Comments