2

I have a multi-valued taxonomy reference field named field_classrooms in a node type. I use below code to delete the value in the field.

$node = Drupal\node\Entity\Node::load('1512');
unset($node->field_classrooms[0]);
$node->save();

I can't figure out what I am doing wrong here.

6

Maybe something like this could help you out

// Get the list of the associated classrooms ...
$classrooms = $node->get('field_classrooms')->getValue();
// ... if there are any associated classrooms ...
if(!empty($classrooms)) {
  foreach($classrooms as $classroom) {
    // ... get the key of the classroom
    $key = array_search(current($classroom), array_column($classrooms, key($classroom)));
    // ... remove the relationship ...
    $node->get('field_classrooms')->removeItem($key);
  }
  // ... and save the node.
  $node->save();
}

If you want to remove a single classroom from the list and you already know the tid

private function removeClassroomFromNode($node, $tid) {
  if(null != $node) {
    // ... get the list of associated classrooms
    $classrooms = $node->get('field_classrooms')->getValue();
    // ... get the key of the classroom
    $key = array_search($tid, array_column($classrooms, 'target_id'));
    // ... remove the classroom
    $node->get('field_classrooms')->removeItem($key);
    // ... save the node.
    $node->save();
  }
}
  • Thanks for the response. I tried removeItem instead of unset but still it doesn't seem to remove the value. It is a multi value field btw. – Pravin Ajaaz May 23 '18 at 9:21
  • The removeItem() method uses unset() api.drupal.org/api/drupal/… – Rockabelly May 23 '18 at 11:18
1

You can use below code for removing items in the reference field in Drupal 8 :

/** @var \Drupal\Core\Entity\ContentEntityBase $entity */
$entity = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

$tids = $entity->get('field_classrooms')->getValue();

$updatedTerms = [];
foreach($tids as $term) {
  if ($term['target_id'] != 35)
    $updatedTerms[] = ['target_id' => $term['target_id']];      
}

$entity->field_notifications = $updatedTerms;

$entity->save();
0

Meanwhile you can take help from this code -

$node = \Drupal\node\Entity\Node::load('1512');
// Removes '0' index element.
$node->set('field_classrooms', array_slice($node->get('field_classrooms')->getValue(), 1));
$node->save();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.