Skip to content

Instantly share code, notes, and snippets.

@ozin7
Last active April 18, 2020 12:32
Show Gist options
  • Save ozin7/570a143791d0fc8b21a9ec37e63c3190 to your computer and use it in GitHub Desktop.
Save ozin7/570a143791d0fc8b21a9ec37e63c3190 to your computer and use it in GitHub Desktop.
Drupal 8: Table drag
<?php
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
if ($this->entities) {
/** @var \Drupal\commerce_promotion\Entity\Promotion $promotion */
foreach ($this->entities as $promotion) {
$form['promotions'][$promotion->id()]['name'] = [
'name' => $form['promotions'][$promotion->id()]['name'],
];
$has_parent = FALSE;
$parent_id = 0;
if ($promotion->hasField('parent') && $promotion->parent->target_id) {
$has_parent = TRUE;
$parent_id = $promotion->parent->target_id;
}
$form['promotions'][$promotion->id()]['name']['parent'] = [
'#type' => 'hidden',
'#default_value' => $parent_id,
'#attributes' => [
'class' => ['promotion-parent'],
],
];
$form['promotions'][$promotion->id()]['name']['depth'] = [
'#type' => 'hidden',
'#default_value' => $has_parent ? 1 : 0,
'#attributes' => [
'class' => ['promotion-depth'],
],
];
$form['promotions'][$promotion->id()]['name']['weight'] = [
'#type' => 'weight',
'#title' => $this->t('Weight for @title', ['@title' => $entity->label()]),
'#title_display' => 'invisible',
'#default_value' => $entity->getWeight(),
'#attributes' => ['class' => ['weight']],
];
$indentation = [];
if ($has_parent) {
$indentation = [
'#theme' => 'indentation',
'#size' => 1,
];
}
$form['promotions'][$promotion->id()]['name']['#prefix'] = !empty($indentation) ? $this->renderer->render($indentation) : '';
$form['promotions'][$promotion->id()]['name']['pid'] = [
'#type' => 'hidden',
'#value' => $promotion->id(),
'#attributes' => [
'class' => ['promotion-id'],
],
];
}
}
$form['promotions']['#tabledrag'][] = [
'action' => 'order',
'relationship' => 'sibling',
'group' => 'weight',
];
$form['promotions']['#tabledrag'][] = [
'action' => 'match',
'relationship' => 'parent',
'group' => 'promotion-parent',
'subgroup' => 'promotion-parent',
'source' => 'promotion-id',
'hidden' => FALSE,
];
$form['promotions']['#tabledrag'][] = [
'action' => 'depth',
'relationship' => 'group',
'group' => 'promotion-depth',
'hidden' => FALSE,
];
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment