Failure or success?
Software is like sex, it's better when it's free.
Linus Torvalds

Inherit the full url of the parent book page by using a Drupal token

Recently I created a book in Drupal using two Content Types. One type called Book Description (which has a cover, an ID and some other CCK fields) and another type called Book Page. So far so good. Problems arose when I tried to setup Pathauto. For the Book Description I entered book/[field_book_id-raw], which worked great. For the Book Pages I needed something like book/[field_book_id-raw]/title-of-my-page. This is where I got stuck.

The problem with this setup is that the CCK fields of Book Description aren't 'known' in the Book Pages. Or more technically, the Tokens of Book Description aren't loaded when Book Pages are displayed. Saving a Book Page therefore resulted in [field_book_id-raw] (literally) in the URL, instead of its value. I needed to get this working, so I wrote a small module.

The book module already comes with some tokens:

  • [book]: The title of the node's book parent.
  • [book_id]: The id of the node's book parent.
  • [bookpath]: The titles of all parents in the node's book hierarchy.
  • [book-raw]: The unfiltered title of the node's book parent. WARNING - raw user input.
  • [bookpath-raw]: The unfiltered titles of all parents in the node's book hierarchy. WARNING - raw user input.
  • [bookpathalias]: URL alias for the parent book.

I expected [bookpathalias] to work, but that resulted in something like book/title-of-the-book/title-of-the-page. None of the tokens did what I wanted. What I needed was a Token that uses the full path of its parent page. After some testing, I got it working using 2 Token hooks:

/**
* Implementation of hook_token_values().
*/
function CUSTOMMODULENAME_token_values($type, $object = NULL, $options = array()) {
  if ($type == 'node') {
    $node = $object;
    $tokens['bookurl-path'] = '';
    if (!empty($node->book['plid'])) {
      $parent = book_link_load($node->book['plid']);
      $tokens['bookurl-path'] = drupal_lookup_path('alias', $parent['href']);
    }
    return $tokens;
  }
}

/**
* Implementation of hook_token_list().
*/
function CUSTOMMODULENAME_token_list($type = 'all') {
  if ($type == 'node' || $type == 'all') {
    $tokens['book']['bookurl-path'] = t("The url of the parents node");
    return $tokens;
  }
}

This creates the token [bookurl-path] which I can use my pathauto settings to get an url like book/12345/title-of-my-page.

Add new comment

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.