Right now, I have it set so that the account page and profile page are the same, not separate. I have a field in my profile called Real Name:

How can I make "Real Name" the heading of the account page and NOT the username? I originally wanted to keep the account pages and profiles separate but I honestly couldn't find a way to access other user's profile pages even while logged in as admin. I couldn't figure out the url... In any case, I suspect the user name would have been the main heading on both pages anyway.....so, how can I manipulate the template to get it to do what I want?

I think it has to do with this code:

print $attributes; > print $title;

in the user item tpl, but I don't know if I can theme these profile fields and do they theme like CCK fields did in D6? I know how to manipulate fields using D6 and CCK....not sure about d7 and the profile fields for this module....

Becky

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

hedley’s picture

To remove the profile title (by default this title is "main profile".), you can copy 'user-profile.tpl.php' from /modules/user into your theme directory, then add this to the file:

<?php
  /** This removes the 'main profile' title **/
  $user_profile['profile_main']['#title'] = "";
?>

BEFORE

<?php print render($user_profile); ?>

Slightly confusing as there is a 'profile.tpl.php' in the profile2 module folder which you may assume you have to edit to remove this title. There may even be a cleaner way to accomplish this with a template preprocess function.

hedley’s picture

To change the content title (defaults to the username) you can use this snippet in a custom module:


function MYMODULE_custom_menu_alter(&$items) {
  $items['user/%user']['title callback'] = MYMODULE_user_page_title;
}

function MYMODULE_user_page_title() {

  if(arg(0) == 'user') {
    // Load uid from url
    $user = user_load(arg(1));
    // Load profile2 entity
    $profile2 = profile2_load_by_user($user->uid);
    // Load fields
    $myfield = field_get_items('profile2', $profile2['main'], 'field_myfield');
    $output = $myfield[0]['safe_value'];
  }

  // Fallback to username if no fields are present
  if(empty($output)) {
    $output = $user->name;
  }
  
  return $output;
  
}

Change 'myfield' to whatever your profile2 field is. and MYMODULE to the name of your module. You may also need to change $profile2['main'] if you have created a custom profile type.

The thing you have to remember here is that the $title is built from the menu system, so you can't use a preprocess_page to edit it. The other way to do this would be to put some similar code into page.tpl.php

Syd Barrett’s picture

Should this go on page.tpl.php?

hoff331’s picture

I have the "profile2 pages" module turned off. When you go to a user profile, the username is the page title.

I have tried using this code and it does not work... I set 'main' to the machine name of my profile type and 'field_myfield' to the machine name of my profile specific field.

Does the module we create need specific profile2 dependencies set in the .info file?

trevorleenc’s picture

I had a heck of a time today trying to get the code here, and the code from a post on Stack Exchange...

anyway...this tinkered and dinkered combo of code from both here works for me, hope this helps save someone some time.


/* -instructions-
   1. create a new custom module...
   2. replace MYMODULENAME with the name of your new custom module
   3. replace "my_custom_profile" with the machine name of your profile
   4. replace "field_mycustomfield_fullname" with the name of the field you wish to use for the page title.
   5. save module, activate, and cross your fingers :)
*/

function MYMODULENAME_menu_alter(&$items) {
  $items['user']['title callback'] = $items['user/%user']['title callback'] = 'MYMODULENAME_user_menu_title';
}

function MYMODULENAME_user_menu_title() {
  $account = user_load(arg(1));
  if ($account) {
    $profile = profile2_load_by_user($account, 'my_custom_profile');
    if ($profile) {
      $fullnames = field_get_items('profile2', $profile, 'field_mycustomfield_fullname');
      if ($fullnames) {
        return $fullnames[0]['value'];
      }
    }
    $output = user_menu_title($account);
  }
  return $output;
}

ref: http://drupal.stackexchange.com/questions/13283/change-page-title-on-use...

elpino’s picture

I found this documentation page https://drupal.org/node/1392716 explaining how to accomplish this using Rules.

It gives the following code so that you can import the rule, and then adjust the conditions and actions to suit your own profiles

{ "rules_generate_a_profile_label" : {
    "LABEL" : "Generate a profile label",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "profile2" ],
    "REQUIRES" : [ "rules", "profile2" ],
    "ON" : [ "profile2_presave" ],
    "IF" : [ { "data_is" : { "data" : [ "profile2:type" ], "value" : "main" } } ],
    "DO" : [
      { "data_set" : {
          "data" : [ "profile2:label" ],
          "value" : "[profile2:user:name]\u0027s [profile2:type:label]"
        }
      }
    ]
  }
}

However it's not working for me for some reason.

museumboy’s picture

I tried to use number 5 as a template.php hook and it works if you flush the cache. However eventually the names revert back to the normal username. Is that why this needs to be a module and cannot be a template.php hook?

bisonbleu’s picture

Issue summary: View changes

NOTE - I'm using the latest dev version (7.x-1.3+4-dev).

I'm displaying profiles on separate pages. Unfortunately,

  • The solution #5 makes it possible to override the My account label in the User menu. Nice! But it doesn't override the profile page title when the option Provide a separate page for editing profiles is checked.
  • The solution in #6 only works for one language on a multilingual website. In my case, French is the default language so in the French UI I get what the Rule is setup for i.e. [profile2:field-member-first-name] [profile2:field-member-last-name]. But when I switch to English, it's back to the default label Member Profile.

The strange part is that when I print_r($profile2); in profile2.tpl.php, the label is fine even when I'm in the English UI.

Profile Object
(
    [pid] => 913
    [type] => membership
    [label] => John Smith
    [uid] => 1
    [created] => 1400781451
    [changed] => 1401378461
    [entityType:protected] => profile2
    [entityInfo:protected] => Array
        (...
bisonbleu’s picture

Priority: Normal » Major
bisonbleu’s picture

In the end the following works perfectly for my use-case. Create a simple module, paste this function into the .module file, change the placeholder snippets (my_module, field_first_name, field_last_name ) and your good to go.

/**
 * Implements hook_profile2_view_alter()
 *
 * Overrides the default title of the Profile2 page using profile fields.
 * Where no profile exists, do nothing i.e. use Profile2's default label.
 *
 */
function my_module_profile2_view_alter($build) {
  // If Devel is enabled, you may uncomment dpm() to find out how
  // you can access the various fields of your profile.
  // dpm($build);
  if (!isset($build['empty'])) {
    $custom_title = $build['field_first_name'][0]['#markup'];
    $custom_title .= ' ' . $build['field_last_name'][0]['#markup'];
    drupal_set_title($custom_title);
  }
}

Don't forget to delete the php end tag (?>) of the .module file!

Anonymous’s picture

The solution in #10 works perfectly. Thanks.

deanflory’s picture

Thanks bisonbleu, #10 worked flawlessly.

My site uses first, middle and last names and I wanted to present all three. Here's the code I used (downloadable files attached):

Module folder name:

profile2_username_title

profile2_username_title.info

name = Profile2 User Name Page Title
description = This custom module allows the user's profile2 page to display the user's name (first middle last) instead of "User Profile".
core = 7.x
dependencies[] = entity
dependencies[] = profile2

profile2_username_title.module

<?php
/**
 * Implements hook_profile2_view_alter()
 *
 * Overrides the default title of the Profile2 page using profile fields.
 * Where no profile exists, do nothing i.e. use Profile2's default label.
 *
 */
function profile2_username_title_profile2_view_alter($build) {
  // If Devel is enabled, you may uncomment dpm() to find out how
  // you can access the various fields of your profile.
  // dpm($build);
  if (!isset($build['empty'])) {
    $custom_title = $build['field_first_name'][0]['#markup'];
    $custom_title .= ' ' . $build['field_middle_name'][0]['#markup'];
    $custom_title .= ' ' . $build['field_last_name'][0]['#markup'];
    drupal_set_title($custom_title);
  }
}
?>
deanflory’s picture

And the .info file:
(just remove the .txt off the end)

deanflory’s picture

It would be great if this were integrated into the profile2 module as a submodule and allow tokens to be inserted and arranged by users on an admin panel since I imagine most every user of the profile2 module would utilize this feature.

qlumbus’s picture

Priority: Major » Normal

Thanks. This is exactly what I am looking for.
Unfortunately I receive the following error message when enabling the module:

Notice: Undefined index: field_first_name in profile2_username_title_profile2_view_alter() (line 14 of /var/www/sites/all/modules/profile2_username_title/profile2_username_title.module).
Notice: Undefined index: field_last_name in profile2_username_title_profile2_view_alter() (line 15 of /var/www/sites/all/modules/profile2_username_title/profile2_username_title.module).
qlumbus’s picture

The Real Name module does the trick as well: https://www.drupal.org/project/realname

bisonbleu’s picture

@qlumbus,

Make sure that the machine names for First name and Last name are set to field_first_name and field_last_name respectively. You can see the machine names in the Manage fields tab of your profile2 type.

ret5’s picture

Fyi - Was able to change the Profile2 Page Title using Rules.

1. Create Rule on Event, "When Profile is Viewed"
2. Set Action "Set A Data Value" where profile2:user:your-profile-type-name:label
3. Set Data Value to use whatever token, url, or text you like.

Hopefully that helps out.

jigish.addweb’s picture

If you want to change page title, you can change directly using Page Title module, pattern replacement.

If you want to change page header, then you need to make small stuff of customization for same. Please find below code snippet for same. This code will be in your theme template file.

function theme_preprocess_page(&$vars, $hook) {
        global $user;
        if(arg(0)=='user' && arg(1)==$user->uid){

                $user_profile_details = profile2_by_uid_load($user->uid, 'profile_type_name');

                if(isset($user_profile_details->field_name_to_display[LANGUAGE_NONE]['0']['value']) && !empty($user_profile_details->field_name_to_display[LANGUAGE_NONE]['0']['value'])) {
                        $vars['title'] = t($user_profile_details->field_name_to_display[LANGUAGE_NONE]['0']['value']);
                }
        }
}

Let me know in case of any further query/concern.

Thanks!

Benoit63’s picture

I spent many time to find a good solution to this problem! The differents issues didn't satisfying me, certainly because i'm not a good drupal themer or developper... The solutions proposed with rules module didn't work for me too, because the modification of title occurs only after a page reload (not on first load), i don't understand why.

Anyway, i finally found a solution adapted in my case (separate page, in particular) thanks to the rules bonus pack module, which allow to create new rules.

Here is my rule :
{ "rules_title_profile_modification" : {
"LABEL" : "Title profile modification",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "profile" ],
"REQUIRES" : [ "rules", "rb_misc", "rb_theme", "profile2" ],
"ON" : { "profile2_view" : [] },
"DO" : [
{ "rb_misc_action_set_title" : { "page_title" : "[profile2:field-name] [profile2:field-fname]" } },
{ "rb_theme_action_set_head_title" : { "head_title" : "[profile2:field-name] [profile2:field-fname]" } }
]
}
}

The rule modify the page title, but also head title.

Hope this could help.

blacklime’s picture

I've found a simple solution to this for anyone interested. It can be difficult to print profile2 fields anywhere other than user-profile.tpl.php - so what you can do to set / change your page title pattern for a user profile (i.e. If you want your title to be something like "Profile2 Field | Site Name"). So I did the following:

  1. Duplicate html.tpl.php and rename it html--user.tpl.php
  2. Strip tags from html--user.tpl.php - this should cause the URL to be the page title (default).
  3. Add tags to user-profile.tpl.php
  4. Set your profile2 field to print within the title tags.
  5. Reload profile page and see the changes.

Example:

Title Tag Starts Here

print $profile['profile_type']->field_name['und'][0]['value']

Title Tag Ends Here

Conclusion:

This may not be the most "valid" way of doing it, but after trying a number of different solutions posted on various forums, I made my own solution. It's quick / dirty, but it works like a charm.

Tweet @blacklimemedia w/ any questions or comments.

luxpir’s picture

For anyone just trying to hide the title on the user page, profile2 or otherwise, I added the following to the template.php file in my theme directory:

<?php
//
// Only act when the first part of the url equals 'user',
// the second part is a number and the third part is empty,
// i.e. is a user page, showing a profile2 profile in my case.
// Then unset the $title variable for the template to hide.
// 

function MY_THEME_NAME_preprocess_page(&$variables) {
    $arg = arg();
    if ($arg[0] == 'user' && is_numeric($arg[1]) && empty($arg[2])) {
        $variables['title'] = false;
    }
}

?>

I actually had to add the snippet from $arg onwards (excluding the final brace, it was already there - added extra whitespace here for clarity - also ignore the php tags, I only added those to give the snippet glorious technicolor) into the existing preprocess_page section, not realising that you couldn't call it twice (drush told me about this error when I cleared the cache). This is cobbled together from a few SE and d.o comments, some of which had syntax errors (additional parentheses) but it did the trick in the end.

Prior to this I tried using Rules, which worked but changed usernames in the DB which I did not realise it would do, and also the realname module suggested here, which did the same. In my case I wanted users to keep their chosen usernames, just didn't want to display them on public profiles (as contact information revealed to members only).

Hope that helps.

NikLP’s picture

With regards to the previous comment, I suspect that

$variables['title'] = false;

might need to be replaced with

unset($variables['title']);

as the templates often use isset($var) to check whether to render the variable or not. I'm open to correction though.

luxpir’s picture

Was some discussion of that at SE where part of the snippet came from. Might be theme dependent? In any case it works as it is for now. Will revisit if problems arise!

tory-w’s picture

#18 worked perfectly.... I have it set up to show the FIRSTNAME and LASTNAMEINITIAL on both the Account/User and Profile 2 pages.

joachim’s picture

There's an actual Real Name module, which may do what you want.

nategasser’s picture

I like #10 but had to make a small change:

if (!isset($build['empty']) && ($build['#bundle'] == 'public_info')) {

because I have more than one profile type, and it throws errors if you look for fields in the wrong profile type.
Note: "public_info" is the machine name of the profile I wanted to use fields from.

rami.sedhom’s picture

It works very nice using Rules as per comment #18

deanflory’s picture

I've just found that the method in #10, 12, 13 above works to make the fields you want render as the page title on the profile2 pages, BUT if you also create a View that uses the Rendered Entity method to display a user's profile as a field, it will change the page title of any page that displays that View as a block.

bisonbleu’s picture

@deanflory, you can achieve what you want by limiting/reducing the scope of the hook_form_alter.

I don't know if this is the best way, but it's one way. The new outer if checks if the body tag of the page contains a class associated to a profile. In my case, that is page-profile-membership. If the profile class is found, then the context is a profile page. If the profile class is NOT found, then the context is different.

function my_module_profile2_view_alter($build) {
  if (strpos ($classes, 'page-profile-membership')) {
    if (!isset($build['empty'])) {
    	$full_name = $build['field_member_first_name'][0]['#markup'];
    	$full_name .= ' ' . $build['field_member_last_name'][0]['#markup'];
    	drupal_set_title($full_name);
    }
  }
}
deanflory’s picture

I've tried your code in #30 bisonbleu and found it didn't work to change the profile2's page title on my site. Also, here's an error I received:

Notice: Undefined variable: classes in profile2_public_username_title_profile2_view_alter() (line 13 of /.../sites/all/modules/profile2_public_username_title/profile2_public_username_title.module).

Here's the exact .module code I used:

<?php
/**
 * Implements hook_profile2_view_alter()
 *
 * Overrides the default title of the Profile2 page using profile fields as long as it matches the specified class for a particular profile type since not doing so will cause page titles on other nodes to be changed by a view that renders the profile in a block used as a field.
 * Where no profile exists, do nothing i.e. use Profile2's default label.
 *
 */
function profile2_public_username_title_profile2_view_alter($build) {
  // If Devel is enabled, you may uncomment dpm() to find out how
  // you can access the various fields of your profile.
  // dpm($build);
  if (strpos ($classes, 'page-profile-public')) {
    if (!isset($build['empty'])) {
    	$full_name = $build['field_preferred_name'][0]['#markup'];
    	$full_name .= ' ' . $build['field_last_name'][0]['#markup'];
    	drupal_set_title($full_name);
    }
  }
}
?>

The class "page-profile-public" exists.

bisonbleu’s picture

As mentioned, my code is specific to my website i.e. does not completely apply to yours or others.

To be more specific, the class page-profile-membership exists on my website because the machine name of my Profile2 profile is membership. In other words, the class name is created as follows: page-profile-[the name of your profile].

The reason why in your case it's page-profile-public is because the machine name of your Profile2 profile is public.

If someone has a Profile2 profile named experts, then the class name to look for will be page-profile-experts.

deanflory’s picture

Uh, yes, I understood all of the class names and altered my code accordingly by changing it to page-profile-public as that is the class being used, but it still does not work. Thanks anyway.

bisonbleu’s picture

FileSize
244.08 KB

Hum... Couple of things...

Here's what I see @ en/profile-membership (my profile)

<body class="html not-front logged-in one-sidebar sidebar-second page-profile-membership page-profile-membership- page-profile-membership-1 i18n-en lang-en section-profile-membership" >

and this @ en/profile-membership/13948 (another user's profile)

<body class="html not-front logged-in one-sidebar sidebar-second page-profile-membership page-profile-membership- page-profile-membership-13948 i18n-en lang-en section-profile-membership" >

What does your <body> tag look like?

Also, I created a Profile2 block (Profiles) view and, like you said, saw that the Our history page title was overridden. Then I added if (strpos ($classes, 'page-profile-membership')) {...} and as you can see in the capture, the page title is back.

So I don't see why it would not work.

 before-and-after.png

sam-elayyoub’s picture

Try to use any module and add one of the codes below (prefer to start your own module and name it something like user_profile_title or so which you can add more codes later for that page)

1- depending on the path/url

function YOUR_MODULE_menu_alter(&$items) {
    // Change the title of user profile pages to the user's name.  Gak.
    $items['user/%user']['title callback'] = 'YOUR_MODULE_user_page_title';
}

function YOUR_MODULE_user_page_title() {
        $output = user_name_full();
 drupal_set_title($output);    // to make sure you change the title even if you are using views within the profile
    return $output;
}

function user_name_full(){

////get path by php //////
if ($path == NULL) {
    $path = $_GET['q'];
  }
  $str = str_replace("user/", "", $alias); // clean the url from any thing else than the name (can be controlled by AutoPath or URL alias )
  $name = $path;

/// or use drupal hook  to get the path///////
  if ($alias = drupal_lookup_path('alias', $path, $path_language)) {
    $str = str_replace("user/", "", $alias); // clean the url from any thing else than the name (can be controlled by AutoPath or URL alias )
    $name = $str;
  }

  return $name;
}

2- depending on your user first name and last name

function YOUR_MODULE_menu_alter(&$items) {
    // Change the title of user profile pages to the user's name.  Gak.
    $items['user/%user']['title callback'] = 'YOUR_MODULE_user_page_title';
}

function YOUR_MODULE_user_page_title() {
    if (arg(0) == 'user') {
        // Load uid from url
        $user = user_load(arg(1));
        // Get the full user name somehow;
        $output = user_full_name($user);
    }
    // Fallback to username if no fields are present
    if (empty($output)) {
        $output = $user->name;
    }
    return $output;
}

function user_full_name($user){
$user_fields = user_load($user->uid);
$firstname = $user->field_name_first['und']['0']['value'];
$lastname = $user->field_name_last['und']['0']['value'];
$title = $firstname . ' ' . $lastname;
return $title;
}

for me I prefer to use always the first one, because it can be changed later through autopath and change auto by changing the url plus no need to load the user profile multiple times

eworwa’s picture

I can confirm that the realname module (https://www.drupal.org/project/realname) worked for me. I'm using Drupal 8.3.7 and installed realname 8.x-1.0-rc1. I'm not sure how this worked in the past, but now I can confirm that keeps the user name as it. I'm not using the profile module thou.

Update: I spoke too soon. This module is not working properly due to a Drupal Core issue (https://www.drupal.org/node/2629286). Looking in the issue queue someone mentioned this other module https://www.drupal.org/project/name, I haven't tried yet but it looks like a good option. If it doesn't work, I will try the Rules approach.

capysara’s picture

Thanks, everyone!

I needed to change the title using the profile on a separate page. I used a variation of #10 and it worked great, but I needed to update the title on the /edit page, too, so I also used hook_form_FORM_ID_alter().

function YOUR_MODULE_form_FORM_ID_form_alter(&$form, &$form_state, $form_id) {
  $custom_title = 'The Profile';
  drupal_set_title($custom_title);
}
RickJ’s picture

Please look at the experimental patch in #3029027: Allow entry and display of profile title.

Is that of any use in relation to issues here?

Richard15’s picture

#19 is the only one worked for me.

The same function ("preprocess page") doesn't print [title] at all, so I couldn't modify it

In template.php it works!

Thanks!