0

I'm trying to use a hook_page_alter() to change make the title of certain pages a link to another page.

This is the code I would like to alter.

function mashavumodule_page_alter(&$page) {
  // get the user id of the patient
  $user_id = $page['content']['system_main']['nodes'][$nid]['field_user_id']['#items'][0]['value'];

  drupal_set_message(l("View Patient Profile", "user/{$user_id}" ));
}

Currently, I have the link outputting as a system message.

Also as a side note, if there is a more elegant way to get the value of the field_user_id, I'd love to know because typing

$page['content']['system_main']['nodes'][$nid]['field_user_id']['#items'][0]['value']

just doesn't seem right.

1 Answer 1

2

I don't think hook_page_alter() is the best place to do this (though I may be wrong), it seems like since you're changing the display of the title it should be done at the theme level.

Personally I'd go for a hook_preprocess_page():

function MYMODULE_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $field_items = field_get_items('node', $node, 'field_user_id');
    $first = array_shift($field_items);

    $user_id = $first['value']; // if 'value' is the column name for your field, it might be 'uid' if you're using a references field, 'target_id' for entity reference, etc.

    $link = l($vars['title'], 'path/for/link');

    $vars['title'] = $link;
  }
}
4
  • Thanks again Clive. Will $_GET['q'] == 'the_page' work even if the url is not of the form .../?q='the_page'?
    – Mike
    Commented May 24, 2012 at 17:21
  • It won't work for the URL alias no, but you could use request_path() instead of $_GET['q'] if you need to test that instead
    – Clive
    Commented May 24, 2012 at 17:43
  • Also, the page that is 'the_page' is a 'node/%'. Will 'node/*' work
    – Mike
    Commented May 24, 2012 at 18:57
  • If you just need to know it's a node page then it's a bit simpler, I've updated the answer
    – Clive
    Commented May 24, 2012 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.