1

i am writing a simple multistep form using ctools on drupal 7. Everything seems to work but i have a one last problem before i finish the task. How can i access the custom user fields (or fieldset i am not sure about the terminology). I've tried to do that by using the function below but it doesn't works and the property is always empty;

function helper_get_default_value_from_profile($fieldset, $key){

  $uid      = helper_is_user_logged_in();
  $account  = user_load($uid);
  $profile  = profile2_load_by_user($account, "cv");

  if(!property_exists($profile, $fieldset))
    return 0;

  if(empty($profile->$fieldset))
    return 0;

  $fieldset_ref = $profile->$fieldset;
  $id           = $fieldset_ref["und"][0]["value"];
  $fieldset_data = field_collection_field_get_entity($id);

  if(!property_exists($fieldset_data, $key))
    return 0;

  if(empty($fieldset_data->$key))
    return 0;

  $user_prop = $fieldset_data->$key;
  return $user_prop["und"][0]["value"];
}
2

It seems like you want to retrieve the value of a single field from a field collection. And that the field collection you want to retrieve a field from is a field of a 'cv' profile2.

The returned value of profile2_load_by_user($account, "cv"); is a Profile entity object. When $fieldset is the (machine) name of a field collection field, then you can retrieve its value using $items = field_get_items('profile2', $profile, $fieldset) (see field_get_items()). This will return an array of field collection values (or FALSE if there is no value for the field). The values are arrays containing a value entry which is the entity id of a field collection entity. You can load the field collection entity for an ID using field_collection_field_get_entity(). Finally, using $key as field name, you can retrieve the values of one of this field collection entity's fields using field_get_items() again.

$items = field_get_items('profile2', $profile, $fieldset);
if ($items) {
  $item = reset($items);
  if (!empty($item['value'])) {
    $field_collection = field_collection_field_get_entity($item);
    if ($field_collection) {
      $items = field_get_items('field_collection', $field_collection, $key);
      if ($items) {
        $item = reset($items);
        return !empty($item['value']) ? $item['value'] : 0;
      }
    }
  }
}
return 0;

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.