function taxonomy_multidelete_terms_form_alter in Taxonomy Multi-delete Terms 8
Implements hook_form_FORM_ID_alter().
File
- ./
taxonomy_multidelete_terms.module, line 33 - Control taxonomy term delete.
Code
function taxonomy_multidelete_terms_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id === 'taxonomy_overview_terms') {
$checkboxes_present = FALSE;
$user = \Drupal::currentUser();
//Exit now if we don't have permissions to multi-delete
if (!$user
->hasPermission('access taxonomy multidelete terms')) {
return;
}
$vocabulary = $form_state
->get([
'taxonomy',
'vocabulary',
]);
$tree = \Drupal::service('entity_type.manager')
->getStorage("taxonomy_term")
->loadTree($vocabulary
->id(), 0, NULL, TRUE);
$term_id = array();
foreach ($tree as $term) {
$term_id[] = $term
->id();
}
foreach ($form['terms'] as $key => $element) {
//If the weight field is present, then the vocabulary is in a state where it can be updated.
if (substr($key, 0, 4) === 'tid:' && isset($form['terms'][$key]['weight'])) {
$checkboxes_present = TRUE;
//Add delete checkbox to table
$form['terms'][$key]['term']['check-delete'] = [
'#type' => 'checkbox',
'#title' => Link::fromTextAndUrl($form['terms'][$key]['term']['#title'], $form['terms'][$key]['term']['#url'])
->toString(),
];
if (count($term_id) == 1) {
$form['terms'][$key]['term']['tid'] = array(
'#type' => 'hidden',
'#value' => $term_id[0],
'#attributes' => array(
'class' => array(
'term-id',
),
),
);
$form['terms'][$key]['term']['depth'] = array(
'#type' => 'hidden',
'#default_value' => 0,
'#attributes' => array(
'class' => array(
'term-depth',
),
),
);
}
//Change root item from a link to a container to avoid showing links twice.
unset($form['terms'][$key]['term']['#title']);
unset($form['terms'][$key]['term']['#url']);
$form['terms'][$key]['term']['#type'] = "container";
}
}
//Make sure we rendered at least one checkbox before adding the delete button and select all header option.
if ($checkboxes_present) {
//Add 'select all' checkbox to the header. Width auto because select all assumes it's the only thing in the column
$form['terms']['#header']['term'] = [
'data' => Markup::create(' ' . t('Name')),
'class' => [
'select-all',
],
'style' => 'width:auto;',
];
$form['actions']['delete'] = [
'#type' => 'submit',
'#value' => t('Delete'),
'#submit' => [
'taxonomy_multidelete_terms_taxonomy_overview_terms_submit',
],
];
$form['#validate'][] = 'taxonomy_multidelete_terms_taxonomy_overview_terms_validate';
$form['#attached']['library'][] = 'core/drupal.tableselect';
}
}
}