Skip to content
Snippets Groups Projects

Resolve #3450455 "Allow multiple replacement"

Files
2
@@ -106,10 +106,13 @@ class TaxonomyReplaceForm extends ContentEntityDeleteForm {
];
$form['new_tid'] = [
'#title' => $this->t('Taxonomy term to use instead'),
'#title' => $this->t('Taxonomy term(s) to use instead'),
'#type' => 'entity_autocomplete',
'#required' => TRUE,
'#tags' => TRUE,
'#target_type' => 'taxonomy_term',
'#description' => $this->t('Separate multiple terms by comma.'),
'#maxlength' => 512,
// Limit the selection to the same vocabulary.
'#selection_settings' => [
'target_bundles' => [
@@ -134,9 +137,11 @@ class TaxonomyReplaceForm extends ContentEntityDeleteForm {
/** @var \Drupal\taxonomy\Entity\Term $old_term */
$old_term = $this->getEntity();
$old_tid = $old_term->id();
$new_tid = $form_state->getValue('new_tid');
if ($old_tid == $new_tid) {
$form_state->setErrorByName('new_tid', $this->t('The replacement term is the same as the current term. Please select a different term.'));
$new_tids = $form_state->getValue('new_tid');
foreach ($new_tids as $new_tid) {
if ($old_tid == $new_tid['target_id']) {
$form_state->setErrorByName('new_tid', $this->t('A replacement term cannot be the same as current term.'));
}
}
}
@@ -145,30 +150,40 @@ class TaxonomyReplaceForm extends ContentEntityDeleteForm {
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$new_tid = $form_state->getValue('new_tid');
/** @var \Drupal\taxonomy\Entity\Term $old_term */
$old_term = $this->getEntity();
/** @var \Drupal\taxonomy\Entity\Term $new_term */
$new_term = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->load($new_tid);
$count = $this->replaceService->replace($old_term, $new_term);
$new_terms = [];
$new_tids = $form_state->getValue('new_tid');
foreach ($new_tids as $new_tid) {
/** @var \Drupal\taxonomy\Entity\Term $new_term */
$new_term = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->load($new_tid['target_id']);
$new_terms[] = $new_term;
}
$count = $this->replaceService->replace($old_term, $new_terms);
// Create a string of the new term names.
$new_term_names = [];
foreach ($new_terms as $newTerm) {
$new_term_names[] = $newTerm->label();
}
$new_term_names = implode(', ', $new_term_names);
$tokens = [
'%nodes' => $count,
'%old_term' => $this->entity->label(),
'%new_term' => $new_term->label(),
'%new_term' => $new_term_names,
];
$this->messenger()->addStatus($this->t('%nodes references to %old_term have been replaced by references to %new_term', $tokens));
// Delete the old term.
parent::submitForm($form, $form_state);
// Redirect to the new taxonomy term.
// Redirect to the first new taxonomy term.
$form_state->setRedirectUrl(new Url('entity.taxonomy_term.canonical', [
'taxonomy_term' => $new_tid,
'taxonomy_term' => $new_terms[0]->id(),
]));
}
Loading