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('type','a')
->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) {
$node->set('field_taxonomy_',$new_term);
$node->save();
}
}
}
}
The code doesn't work.
$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