0

I am new to Drupal 8. What I want to achieve is to delete the taxonomy term (entity reference) and its association from the nodes where it is referenced. Node has multiple languages, revisions, content moderation, etc. Below is the code I used to delete the association from node followed by delete the term.

$tid = 20;
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['field_mycollections' => $tid]);
foreach($nodes as $node){
      if(null != $node) {
          $collections = $node->get('field_mycollections')->getValue();
          $index = array_search($tid, array_column($collections, 'target_id'));
          $node->get('field_mycollections')->removeItem($index);
          $node->save();
      }
}
$term = Term::load($tid);
$term->delete();

$tid is again coming from foreach (foreach $tids as $tid {}).

This way, the term is deleted, node association is removed. Now the issue is, when I edit the translated node (say spanish) through UI, I am getting error "Non-translatable fields can only be changed when updating the original language.". If I resave english version (default language) through UI and then saves spanish version, it saves. I assume, this is because "removeItem" method removes the term from node__field_collections table but not from the node_revision__field_collections table.

Can anyone please help me here on resolution?

1
  • Instead of invoking ::removeItem(), try modifying the $collections variable and then writing it back to the entity with ::setValue(). – Beau Oct 8 '20 at 13:55

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.