When theming a user profile powered by profile2, I need to move fields around and outside the profile2 main content, and I wonder what's the proper way to target the fields inside the profile. For example, I want to render the profile photo outside the main profile2 content. This is what I have to do below. I feel there must be an easier way to do this, but because the key of the array is the profile2 entity id, it makes the code more complicated.

function mymodule_preprocess_user_profile(&$vars) {
  // Prepares the photo to be rendered outside the main profile content.
  // We need the profile id to match the element in the render array.
  $vars['pid'] = !empty($vars['user_profile']['profile_mymodule_profile']['view']['profile2']) ? key($vars['user_profile']['profile_mymodule_profile']['view']['profile2']) :  NULL;
}

And in user-profile.tpl.php:

// Print the photo only:
print render($user_profile['profile_mymodule_profile']['view']['profile2'][$pid]['field_mymodule_photo']);
// And further down, print the rest of the profile2 content...
print render($user_profile);

Comments

dave bruns’s picture

This is an old thread, but I have the same question, and one more:

1. What is the right way to render a single profile2 profile field when working in a template (i.e. user-profile.tpl.php)?

2. Is there an easy way to hide a particular profile2 field when working in a template? It's easy to hide a profile, or something like the title for a profile:

	hide($user_profile['profile_main']);
	$user_profile['profile_main']['#title'] = NULL;

But it is there a way to hide a field that's nested deeply in a profile, under the $pid?

scotwith1t’s picture

Status: Active » Fixed

I did this, assuming that each user would only have one instructor profile (mine are for teachers):

in template.php, if the field is required, i just set it and forget it...

foreach ($variables['user_profile']['profile_instructor']['view']['profile2'] as $teacher) {
  $variables['fname'] = $teacher['field_instructor_fname'];
  $variables['lname'] = $teacher['field_instructor_lname'];
  etc, etc...
}

...if it's optional...

isset($teacher['field_instructor_audio_sample']) ? $variables['audio'] = $teacher['field_instructor_audio_sample'] : '';

...then, in the user-profile.tpl.php, for simple strings and such,

print render($fname);

...will do just fine...or if it is a renderable array, like something like a fivestar rating or embedded audio thing...

if (isset($audio) {
print render($audio)
}

Hope that helps!

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

faqing’s picture

The easiest way:

<?php
global $user;
$uid = user_load($user->uid);
$profile_mymodule_profile=profile2_load_by_user($uid, 'mymodule_profile');
?>
print drupal_render(field_view_field('profile2', $profile_mymodule_profile, 'field_mymodule_photo', 'value'));

lguigo’s picture

Thank you !!!