I'm using this code in a custom module to pull a field ('field_full_name') from a profile ('partner'):

function mymod_username_alter(&$name, $account) {
  if (isset($account->uid)) {
    $profile = profile2_load_by_user($account, 'partner');
    $name = field_view_value('profile2', $profile, 'field_full_name', $profile->field_full_name[LANGUAGE_NONE][0], 'display', LANGUAGE_NONE);
  }
}

However, when I do that, I get this error:

Notice: Trying to get property of non-object in mymod_username_alter() (line 291 of [...]\mymod.module).
EntityMalformedException: Missing bundle property on entity of type profile2. in entity_extract_ids() (line 7405 of [...]\includes\common.inc).

The entity in $profile looks fine to me (see attachement).

Any ideas what could be wrong?

CommentFileSizeAuthor
entity-dump.txt9.84 KBaskibinski

Comments

fago’s picture

Category: feature » support
shendric’s picture

Version: 7.x-1.1 » 7.x-1.2

I'm having a similar issue, where if I try to load a profile for a user that doesn't have one, I get this error. Is there a way to check to see if a profile is there first, before trying to load it?

firfin’s picture

Status: Active » Closed (works as designed)

You could put a conditional statement before trying to use the profile? In the example above you could replace
$name = ...
with

if (profile) {
  name = ...

Does this help you out?

Also marked #1283996: EntityMalformedException and #1818774: Error displaying empty field as a duplicates of this issue.

firfin’s picture

Here is a snippet I used in a computed field. Hope this clears up how to get field values from profile entity without getting MalFormedException messages.

$prof2 = profile2_load_by_user(arg(1), 'initiatiafnemer');

if ($prof2) {    // this check is to prevent malformedexception 
  $field_first = field_get_items('profile2', $prof2, 'field_first'); 
  $field_first = $field_first[0]['value'];

  $field_second = field_get_items('profile2', $prof2, 'field_second');
  $field_second = $field_second[0]['value'];

  $output = "first $field_first and then $field_second";
}
$entity_field[0]['value'] = $output;

Also marked #1839794: How to access entity in hook_form_alter as a duplicate.

prezaeis’s picture

Hia, Im trying to achieve the same thing, i took a look at ur link u provided but couldnt figure out how to implement it in to my code, do u mind helping me? Im trying to print fields from the users profile2 profile on to the user-profile.tpl.php page, im using the code below but i only want it executed if its not empty. Any ideas?

<?php 
$profile = profile2_load_by_user($elements['#account']);
print $profile['main']->field_twitter_id['und'][0]['value'] }; 
?>

Thank u in advance

firfin’s picture

Put it in an if statement? Some thing like
if ( !empty( $profile['main']->field_twitter_id['und'][0]['value'])) {

Good luck with it!