View source
<?php
namespace Drupal\taxonomy\Form;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Pager\PagerManagerInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Drupal\taxonomy\VocabularyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class OverviewTerms extends FormBase {
use DeprecatedServicePropertyTrait;
protected $deprecatedProperties = [
'entityManager' => 'entity.manager',
];
protected $moduleHandler;
protected $entityTypeManager;
protected $storageController;
protected $termListBuilder;
protected $renderer;
protected $entityRepository;
protected $pagerManager;
public function __construct(ModuleHandlerInterface $module_handler, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer = NULL, EntityRepositoryInterface $entity_repository = NULL, PagerManagerInterface $pager_manager = NULL) {
$this->moduleHandler = $module_handler;
$this->entityTypeManager = $entity_type_manager;
$this->storageController = $entity_type_manager
->getStorage('taxonomy_term');
$this->termListBuilder = $entity_type_manager
->getListBuilder('taxonomy_term');
$this->renderer = $renderer ?: \Drupal::service('renderer');
if (!$entity_repository) {
@trigger_error('Calling OverviewTerms::__construct() with the $entity_repository argument is supported in drupal:8.7.0 and will be required before drupal:9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
$entity_repository = \Drupal::service('entity.repository');
}
$this->entityRepository = $entity_repository;
if (!$pager_manager) {
@trigger_error('Calling OverviewTerms::__construct() without the $pager_manager argument is deprecated in drupal:8.8.0 and the $pager_manager argument will be required in drupal:9.0.0. See https://www.drupal.org/node/2779457', E_USER_DEPRECATED);
$pager_manager = \Drupal::service('pager.manager');
}
$this->pagerManager = $pager_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('module_handler'), $container
->get('entity_type.manager'), $container
->get('renderer'), $container
->get('entity.repository'), $container
->get('pager.manager'));
}
public function getFormId() {
return 'taxonomy_overview_terms';
}
public function buildForm(array $form, FormStateInterface $form_state, VocabularyInterface $taxonomy_vocabulary = NULL) {
$form_state
->set([
'taxonomy',
'vocabulary',
], $taxonomy_vocabulary);
$vocabulary_hierarchy = $this->storageController
->getVocabularyHierarchyType($taxonomy_vocabulary
->id());
$parent_fields = FALSE;
$page = $this
->getRequest()->query
->get('page') ?: 0;
$page_increment = $this
->config('taxonomy.settings')
->get('terms_per_page_admin');
$page_entries = 0;
$before_entries = 0;
$after_entries = 0;
$root_entries = 0;
$back_step = NULL;
$forward_step = 0;
$current_page = [];
$delta = 0;
$term_deltas = [];
$tree = $this->storageController
->loadTree($taxonomy_vocabulary
->id(), 0, NULL, TRUE);
$tree_index = 0;
do {
if (empty($tree[$tree_index])) {
break;
}
$delta++;
if ($page && $page * $page_increment > $before_entries && !isset($back_step)) {
$before_entries++;
continue;
}
elseif ($page_entries > $page_increment && isset($complete_tree)) {
$after_entries++;
continue;
}
$term = $tree[$tree_index];
if (isset($term->depth) && $term->depth > 0 && !isset($back_step)) {
$back_step = 0;
while ($pterm = $tree[--$tree_index]) {
$before_entries--;
$back_step++;
if ($pterm->depth == 0) {
$tree_index--;
continue 2;
}
}
}
$back_step = isset($back_step) ? $back_step : 0;
if ($page_entries >= $page_increment + $back_step + 1 && $term->depth == 0 && $root_entries > 1) {
$complete_tree = TRUE;
$after_entries++;
continue;
}
if ($page_entries >= $page_increment + $back_step) {
$forward_step++;
}
$page_entries++;
$term_deltas[$term
->id()] = isset($term_deltas[$term
->id()]) ? $term_deltas[$term
->id()] + 1 : 0;
$key = 'tid:' . $term
->id() . ':' . $term_deltas[$term
->id()];
if ($page_entries == 1) {
$form['#first_tid'] = $term
->id();
}
if ($term->parents[0] == 0) {
$root_entries++;
}
$current_page[$key] = $term;
} while (isset($tree[++$tree_index]));
$total_entries = $before_entries + $page_entries + $after_entries;
$this->pagerManager
->createPager($total_entries, $page_increment);
$user_input = $form_state
->getUserInput();
if (!empty($user_input)) {
$order = array_flip(array_keys($user_input['terms']));
$current_page = array_merge($order, $current_page);
foreach ($current_page as $key => $term) {
if (is_array($user_input['terms'][$key]) && is_numeric($user_input['terms'][$key]['term']['tid'])) {
$current_page[$key]->depth = $user_input['terms'][$key]['term']['depth'];
}
else {
unset($current_page[$key]);
}
}
}
$args = [
'%capital_name' => Unicode::ucfirst($taxonomy_vocabulary
->label()),
'%name' => $taxonomy_vocabulary
->label(),
];
if ($this
->currentUser()
->hasPermission('administer taxonomy') || $this
->currentUser()
->hasPermission('edit terms in ' . $taxonomy_vocabulary
->id())) {
switch ($vocabulary_hierarchy) {
case VocabularyInterface::HIERARCHY_DISABLED:
$help_message = $this
->t('You can reorganize the terms in %capital_name using their drag-and-drop handles, and group terms under a parent term by sliding them under and to the right of the parent.', $args);
break;
case VocabularyInterface::HIERARCHY_SINGLE:
$help_message = $this
->t('%capital_name contains terms grouped under parent terms. You can reorganize the terms in %capital_name using their drag-and-drop handles.', $args);
break;
case VocabularyInterface::HIERARCHY_MULTIPLE:
$help_message = $this
->t('%capital_name contains terms with multiple parents. Drag and drop of terms with multiple parents is not supported, but you can re-enable drag-and-drop support by editing each term to include only a single parent.', $args);
break;
}
}
else {
switch ($vocabulary_hierarchy) {
case VocabularyInterface::HIERARCHY_DISABLED:
$help_message = $this
->t('%capital_name contains the following terms.', $args);
break;
case VocabularyInterface::HIERARCHY_SINGLE:
$help_message = $this
->t('%capital_name contains terms grouped under parent terms', $args);
break;
case VocabularyInterface::HIERARCHY_MULTIPLE:
$help_message = $this
->t('%capital_name contains terms with multiple parents.', $args);
break;
}
}
$edited_term_ids = array_map(function ($item) {
return $item
->id();
}, $current_page);
$pending_term_ids = array_intersect($this->storageController
->getTermIdsWithPendingRevisions(), $edited_term_ids);
if ($pending_term_ids) {
$help_message = $this
->formatPlural(count($pending_term_ids), '%capital_name contains 1 term with pending revisions. Drag and drop of terms with pending revisions is not supported, but you can re-enable drag-and-drop support by getting each term to a published state.', '%capital_name contains @count terms with pending revisions. Drag and drop of terms with pending revisions is not supported, but you can re-enable drag-and-drop support by getting each term to a published state.', $args);
}
$update_tree_access = AccessResult::allowedIf(empty($pending_term_ids) && $vocabulary_hierarchy !== VocabularyInterface::HIERARCHY_MULTIPLE);
$form['help'] = [
'#type' => 'container',
'message' => [
'#markup' => $help_message,
],
];
if (!$update_tree_access
->isAllowed()) {
$form['help']['#attributes']['class'] = [
'messages',
'messages--warning',
];
}
$errors = $form_state
->getErrors();
$row_position = 0;
$access_control_handler = $this->entityTypeManager
->getAccessControlHandler('taxonomy_term');
$create_access = $access_control_handler
->createAccess($taxonomy_vocabulary
->id(), NULL, [], TRUE);
if ($create_access
->isAllowed()) {
$empty = $this
->t('No terms available. <a href=":link">Add term</a>.', [
':link' => Url::fromRoute('entity.taxonomy_term.add_form', [
'taxonomy_vocabulary' => $taxonomy_vocabulary
->id(),
])
->toString(),
]);
}
else {
$empty = $this
->t('No terms available.');
}
$form['terms'] = [
'#type' => 'table',
'#empty' => $empty,
'#header' => [
'term' => $this
->t('Name'),
'operations' => $this
->t('Operations'),
'weight' => $update_tree_access
->isAllowed() ? $this
->t('Weight') : NULL,
],
'#attributes' => [
'id' => 'taxonomy',
],
];
$this->renderer
->addCacheableDependency($form['terms'], $create_access);
foreach ($current_page as $key => $term) {
$form['terms'][$key] = [
'term' => [],
'operations' => [],
'weight' => $update_tree_access
->isAllowed() ? [] : NULL,
];
$term = $this->entityRepository
->getTranslationFromContext($term);
$form['terms'][$key]['#term'] = $term;
$indentation = [];
if (isset($term->depth) && $term->depth > 0) {
$indentation = [
'#theme' => 'indentation',
'#size' => $term->depth,
];
}
$form['terms'][$key]['term'] = [
'#prefix' => !empty($indentation) ? $this->renderer
->render($indentation) : '',
'#type' => 'link',
'#title' => $term
->getName(),
'#url' => $term
->toUrl(),
];
$form['terms'][$key]['#attributes']['class'] = [];
if (in_array($term
->id(), $pending_term_ids)) {
$form['terms'][$key]['#attributes']['class'][] = 'color-warning';
$form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term--pending-revision';
}
if ($update_tree_access
->isAllowed() && count($tree) > 1) {
$parent_fields = TRUE;
$form['terms'][$key]['term']['tid'] = [
'#type' => 'hidden',
'#value' => $term
->id(),
'#attributes' => [
'class' => [
'term-id',
],
],
];
$form['terms'][$key]['term']['parent'] = [
'#type' => 'hidden',
'#default_value' => $term->parents[0],
'#attributes' => [
'class' => [
'term-parent',
],
],
];
$form['terms'][$key]['term']['depth'] = [
'#type' => 'hidden',
'#default_value' => $term->depth,
'#attributes' => [
'class' => [
'term-depth',
],
],
];
}
$update_access = $term
->access('update', NULL, TRUE);
$update_tree_access = $update_tree_access
->andIf($update_access);
if ($update_tree_access
->isAllowed()) {
$form['terms'][$key]['weight'] = [
'#type' => 'weight',
'#delta' => $delta,
'#title' => $this
->t('Weight for added term'),
'#title_display' => 'invisible',
'#default_value' => $term
->getWeight(),
'#attributes' => [
'class' => [
'term-weight',
],
],
];
}
if ($operations = $this->termListBuilder
->getOperations($term)) {
$form['terms'][$key]['operations'] = [
'#type' => 'operations',
'#links' => $operations,
];
}
if ($parent_fields) {
$form['terms'][$key]['#attributes']['class'][] = 'draggable';
}
if ($row_position < $back_step || $row_position >= $page_entries - $forward_step) {
$form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-preview';
}
if ($row_position !== 0 && $row_position !== count($tree) - 1) {
if ($row_position == $back_step - 1 || $row_position == $page_entries - $forward_step - 1) {
$form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-top';
}
elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) {
$form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-bottom';
}
}
foreach ($errors as $error_key => $error) {
if (strpos($error_key, $key) === 0) {
$form['terms'][$key]['#attributes']['class'][] = 'error';
}
}
$row_position++;
}
$this->renderer
->addCacheableDependency($form['terms'], $update_tree_access);
if ($update_tree_access
->isAllowed()) {
if ($parent_fields) {
$form['terms']['#tabledrag'][] = [
'action' => 'match',
'relationship' => 'parent',
'group' => 'term-parent',
'subgroup' => 'term-parent',
'source' => 'term-id',
'hidden' => FALSE,
];
$form['terms']['#tabledrag'][] = [
'action' => 'depth',
'relationship' => 'group',
'group' => 'term-depth',
'hidden' => FALSE,
];
$form['terms']['#attached']['library'][] = 'taxonomy/drupal.taxonomy';
$form['terms']['#attached']['drupalSettings']['taxonomy'] = [
'backStep' => $back_step,
'forwardStep' => $forward_step,
];
}
$form['terms']['#tabledrag'][] = [
'action' => 'order',
'relationship' => 'sibling',
'group' => 'term-weight',
];
}
if ($update_tree_access
->isAllowed() && count($tree) > 1) {
$form['actions'] = [
'#type' => 'actions',
'#tree' => FALSE,
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Save'),
'#button_type' => 'primary',
];
$form['actions']['reset_alphabetical'] = [
'#type' => 'submit',
'#submit' => [
'::submitReset',
],
'#value' => $this
->t('Reset to alphabetical'),
];
}
$form['pager_pager'] = [
'#type' => 'pager',
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
uasort($form_state
->getValue('terms'), [
'Drupal\\Component\\Utility\\SortArray',
'sortByWeightElement',
]);
$vocabulary = $form_state
->get([
'taxonomy',
'vocabulary',
]);
$changed_terms = [];
$tree = $this->storageController
->loadTree($vocabulary
->id(), 0, NULL, TRUE);
if (empty($tree)) {
return;
}
$weight = 0;
$term = $tree[0];
while ($term
->id() != $form['#first_tid']) {
if ($term->parents[0] == 0 && $term
->getWeight() != $weight) {
$term
->setWeight($weight);
$changed_terms[$term
->id()] = $term;
}
$weight++;
$term = $tree[$weight];
}
$level_weights = [];
foreach ($form_state
->getValue('terms') as $tid => $values) {
if (isset($form['terms'][$tid]['#term'])) {
$term = $form['terms'][$tid]['#term'];
if ($values['term']['parent'] == 0 && $term
->getWeight() != $weight) {
$term
->setWeight($weight);
$changed_terms[$term
->id()] = $term;
}
elseif ($values['term']['parent'] > 0) {
$level_weights[$values['term']['parent']] = isset($level_weights[$values['term']['parent']]) ? $level_weights[$values['term']['parent']] + 1 : 0;
if ($level_weights[$values['term']['parent']] != $term
->getWeight()) {
$term
->setWeight($level_weights[$values['term']['parent']]);
$changed_terms[$term
->id()] = $term;
}
}
if ($values['term']['parent'] != $term->parents[0]) {
$term->parent->target_id = $values['term']['parent'];
$changed_terms[$term
->id()] = $term;
}
$weight++;
}
}
for ($weight; $weight < count($tree); $weight++) {
$term = $tree[$weight];
if ($term->parents[0] == 0 && $term
->getWeight() != $weight) {
$term->parent->target_id = $term->parents[0];
$term
->setWeight($weight);
$changed_terms[$term
->id()] = $term;
}
}
if (!empty($changed_terms)) {
$pending_term_ids = $this->storageController
->getTermIdsWithPendingRevisions();
if (array_intersect_key(array_flip($pending_term_ids), $changed_terms)) {
$this
->messenger()
->addError($this
->t('The terms with updated parents have been modified by another user, the changes could not be saved.'));
$form_state
->setRebuild();
return;
}
foreach ($changed_terms as $term) {
$term
->save();
}
$this
->messenger()
->addStatus($this
->t('The configuration options have been saved.'));
}
}
public function submitReset(array &$form, FormStateInterface $form_state) {
$vocabulary = $form_state
->get([
'taxonomy',
'vocabulary',
]);
$form_state
->setRedirectUrl($vocabulary
->toUrl('reset-form'));
}
}