Example: Programatically adding field collection entries to a Profile2 profile

Public

The Drupal 7 Profile2 module is the successor to the Drupal 6 core profile module. Profiles created with Profile2 are entities and can accept Field Collection fields.

This example shows how to programmatically add a field collection entry to a Profile2 profile.

</> CopyGet raw version
php
  1. <?php
  2. $user_uid = 20;
  3. $profile_name = 'awards';
  4.  
  5. // Load the profile we're adding the field to
  6. $profile_entity = profile2_load_by_user($user_uid, $profile_name);
  7.  
  8. // Define the values of the new field
  9. $values = array();
  10. $values['field_name'] = 'field_award'; // field collection name
  11. $values['field_award_name'][LANGUAGE_NONE][0]['value'] = $award_name;
  12. $values['field_award_year'][LANGUAGE_NONE][0]['value'] = $award_year;
  13.  
  14. // Create the field collection entry and associate it with the profile
  15. $field_entity = entity_create('field_collection_item', $values);
  16. $field_entity->setHostEntity('profile2', $profile_entity);
  17. $field_entity->save();
  18. ?>