Programatically create field collection into Profile2 on new user creation I've set up my own custom multi-step registration form, because I just couldn't find a way of making anything out there do what I want. I've found other questions on here like this one and this one which have basically got me 95% there. My main problem now is that I've got a series of field collections in my Profile2 fields, and I just can't seem to find out what my code needs to be in order to get it done properly.

*At this point in the code I've created a new user ($user), and their profile2 ($profile2) and I'm trying to format my fields from my form so that I can throw them all into the $profile2 object.

field_activities


field_start_year
field_end_year
field_text


My code so far is:

$field_collection = entity_create('field_collection_item', array('field_name' =&gt; 'field_activities'));
$field_collection-&gt;setHostEntity('profile', $profile2);
$field_collection-&gt;field_start_year = $entry['start_year'];
$field_collection-&gt;field_end_year = $entry['end_year'];
$field_collection-&gt;field_text = $entry['text'];
$field_collection-&gt;save(FALSE);


And the error I'm getting is:


  Fatal error: Call to a member function setHostEntity() on a non-object


Which would make more sense to me if $profile2 wasn't an object, but it is.

I've got too many unknowns to figure this out at the moment, is it the right code? can I build a create a field collection item on a newly created profile2 object? do I populate all the fields of the profile object first, and then once it's saved, then add the field collections, etc.
Fatal error: Call to a member function setHostEntity() on a non-object


The error means that you are trying to call setHostEntity() method on a non-object, in other words the $field_collection is not an object (NULL probably).

So please check one line before, which is:

$field_collection = entity_create('field_collection_item', array('field_name' =&gt; 'field_activities'));


So basically you are trying to load field_activities field collection, but it is not there, therefore your $field_collection is FALSE as per entity_create  API:


  Return value: A new instance of the entity type or FALSE if there is no information for the given entity type.


Therefore please make sure your field_activities exists as field collection (e.g. at /admin/structure/field-collections), or add additional failing scenario to your code, so when $field_collection is FALSE, do not execute further code.

For valid examples using field collections, check: Entity metadata wrappers page.