0

My user structure have a multiple field "foo" of type "FieldCollection". From a custom module, I want create programmatically several fieldcollection item and add them to the current user.

Without any loop, when I add only one new FieldCollection item to the user, its work. But, when I want user a loop for add several FieldCollection, only the first item is added. I mean :

With some light php :

// In my module
    // some operations and prepare the datas structure
    foreach(datas as data){ // count(datas) = 2, by example
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $field_collection_foo = FieldCollectionItem::create(array('field_name' => "field_foo"));
        $field_collection_foo->set("field_data",$data);       
        $field_collection_foo->setHostEntity($user);
        $field_collection_foo->save();
    }

Then if I go to the user edit page from the back office, I see only the item datas[0] added, not datas[0] datas[1]

Where is my mistake ?

UPDATE (add some test) :

I think I find, I do an another $user->save somewhere in my module and I think its it who save the wrong value :) Ill test it

1

Make sure you've configured the cardinality of the field collection foo as unlimited (or at least anything more than 1) under "Field settings".

Also double check the name that you are passing to the FieldCollectionItem::create() method. It shouldn't be the label name but the machine name of your foo field collection, which will probably be field_foo:

$field_collection_foo = FieldCollectionItem::create(
  array('field_name' => "field_foo")
);

This also applies to the subfield_data (in your field collection item):

$field_collection_foo->set("field_subfield_data", $data);
  • Thanks for your answer :) its an ilimited field, I can add manually multiple value from the edit page by example. The 'field_' missing is a copy mistake, Ill correct my main post. As I said, after my foreach instruction I see the first data in the collection field. Ill do some test, Ill add them in my main post – user2137454 Jan 7 '17 at 20:02
  • 1
    Ok, I see now. A minor side-note: I'd move the User::load() out of the foreach() right above it so you won't be loading the user multiple times but only once. – baikho Jan 7 '17 at 20:53
  • Yes , it was that , my problem is solved :) – user2137454 Jan 7 '17 at 22:55

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.