1

I have a multiple values field on the user entity. This field is field_data.

There are several values in this field. I want to delete all of them.

I tried the following code:

for ($i = 0; $i < count($user->field_data->value()); $i++) {
    $user->field_data[$i]->delete();
}

But I get errors about ->delete() not being a method on this object. I also tried with ->clear() to no avail.

I've been looking for examples on Google for how to do this, but my Google-fu is not so strong today.

  • 1
    I think you are looking for this solution. – Anil Sagar Sep 26 '12 at 9:32
  • @AnilSagar The solution provided in the answer doesn't use the wrapper. (which means it's language dependant, and others drawbacks as well) – Florian Margaine Sep 26 '12 at 9:56
3

Well, I solved it. The answer is kind of tricky.

You can't delete a value in a multiple values field. However, you can set it to "empty". When it's empty, it's removed.

Here is the code to use:

// Also, note the ->count() method
for ($i = 0; $i < $user->field_data->count(); $i++) {
  $user->field_data[$i]->set();
}

This way, values are now empty and the multiple fields have no value left. It's well shown in the UI too and the deltas are correctly handled in the database.

| improve this answer | |
  • in php 7.2: ArgumentCountError: Too few arguments to function EntityDrupalWrapper::set(), 0 passed – ferriol May 23 '18 at 12:25

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.