I have 2 taxonomy terms with the same name (knight(2) and knight(6)) in my Drupal 8 Project; both terms have been used with nodes.

I want to replace knight(6) with knight(2) in all the nodes. I created the following custom form.


The submission handler code is the following one.

  public function submitForm(array &$form, FormStateInterface $form_state) {
  $values =  $form_state->getValues();
  $old_term = $values['old_taxonomy_term'];
  $new_term = $values['new_taxonomy_term'];
  $query = \Drupal::entityQuery('node')
    ->condition('field_taxonomy_', $old_term, '=');
  $results = $query->execute();

  foreach ($results as $nid) {
    $node = \Drupal\node\Entity\Node::load($nid);
    $abc = $node->get('field_taxonomy_')->referencedEntities(); 
    foreach ($abc as $key => $value) {
      $value = reset($value);
      if ($key['tid'] == $old_term) {

The code doesn't work.

  • Instead of deleting the other question, and re-asking a duplicate question, you should have edited the existing question. Deleted questions with a negative score may question-ban you, which means you cannot ask anymore questions, as it happened in this case. – kiamlaluno Oct 29 '20 at 10:57
  • @kiamlaluno Your Point Noted. Sorry! As a new contributor, I Hadn't idea about that. Even I tried to edit the previous question but it was showing me your question is closed. – White Hat Junior Oct 29 '20 at 11:17
  • @kiamlaluno Thanks for correcting me. – White Hat Junior Oct 29 '20 at 11:20
  • Closed questions can still be edited, as correcting an off-topic question to make it on-topic is the correct action to take. – kiamlaluno Oct 29 '20 at 11:35
  • What is $abc lol. You're actually loading the term objects with ->referencedEntities(); you should instead be doing ->getValue(); – No Sssweat Oct 29 '20 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.