Example: Programmatically adding field collection entries to a Profile2 profile

Last updated on
30 April 2025

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.

  $user_uid = 20;
  $profile_name = 'awards';
  
  // Load the profile we're adding the field to
  $profile_entity = profile2_load_by_user($user_uid, $profile_name);

  // Define the values of the new field
  $values = array();
  $values['field_name'] = 'field_award'; // field collection name
  $values['field_award_name'][LANGUAGE_NONE][0]['value'] = $award_name;
  $values['field_award_year'][LANGUAGE_NONE][0]['value'] = $award_year;

  // Create the field collection entry and associate it with the profile
  $field_entity = entity_create('field_collection_item', $values);
  $field_entity->setHostEntity('profile2', $profile_entity);
  $field_entity->save();

Help improve this page

Page status: Not set

You can: