3

I have a custom content type with a field (id is field_link_to_persona) that is multi-valued text. In my UI I have checkboxes that correspond to values in that field and if I uncheck the box and save I want to remove the value from the field.

I load the node like this:

$nodes = \Drupal::entityTypeManager()
            ->getStorage('node')
            ->loadByProperties(['type' => 'document', 'nid' => $docID ]);

            $node = reset($nodes);

I can add new values like this:

$node->field_link_to_persona[] = $newValue;

But how do I remove one? I tried

$node->field_link_to_persona->removeItem($id);

But I keep getting exceptions about the index not existing.

Any help would be appreciated. I'm somewhat new to drupal so no detail is too trivial :)

2
  • 2
    This works if you provide an existing index. You can get a list: print_r(array_keys($node->field_name->getValue()));
    – 4uk4
    Commented Jan 19, 2018 at 19:04
  • @jeff.eynon have you tried assign updated array by $node->field_foo = $updated_array ?
    – Codium
    Commented Dec 3, 2020 at 10:16

1 Answer 1

6

I recently ran into this same issue. Here is how I was able to make this work. In my case, I was working with a user but it can be easily updated for a node as well.

$user = User::load(\Drupal::currentUser()->id());
$id_to_remove = '81' // Make sure to update this to be the actual id you want to remove through something like $term->id().

// Get the field
$my_field = $user->get('field_my_field');
$my_field_values = $my_field->getValue();

// Get the index to remove
$index_to_remove = array_search($id_to_remove,array_column($my_field_values,'target_id'));

// Actually remove the item
$my_field->removeItem($index_to_remove);

// save the user
$user->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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