Programatically create a profile2 record on user insert example

Last updated on 08/07/2016
/**
 * Implements HOOK_user_insert().
 *
 * Populate the Full name and user picture field to profile2.
 */
function HOOK_user_insert(&$edit, $account, $category) {
  if ($category == 'account' && !empty(trim($account->full_name))) {
    $full_name = check_plain($account->full_name);
 
    // New "nicknames" profile record as there is no profile2 entity yet.
    $profile2 = profile2_create(array('type' => 'nicknames', 'uid' => $account->uid));
    profile2_save($profile2);
 
    // Populate Full Name.
    $profile2->field_fullname[LANGUAGE_NONE][0]['value'] = $full_name;
 
    // Try to populate a default User Avatar.
    $picture_field_info = field_info_field('field_user_picture');
    if (!empty($picture_field_info['settings']['default_image'])) {
      $file = file_load($picture_field_info['settings']['default_image']);
      if (!empty($file->fid)) {
        $profile2->field_user_picture[LANGUAGE_NONE][] = array(
          'fid' => $file->fid,
          'filename' => $file->filename,
          'filemime' => $file->filemime,
          'uid' => 1,
          'uri' => $file->uri,
          'status' => 1
        );
      }
    }
 
    profile2_save($profile2);
  }
}