I am trying to build a Drupal site that changes the background depending on what section of the site a visitor is looking at. I have some child pages that should inherit the parent page's background.

I am doing this by adding a class to the BODY tag, and specifying the background in CSS through that class.

Everything works, but I nevertheless get the following error:

Notice: Undefined offset: 1 in MYTHEME_preprocess_html() (line 23 of template.php)

I am using the following code to detect what section of the site is active, and to add a sanitized version of the parent page as a CSS class:

function MYTHEME_preprocess_html(&$variables) {

$menuParent = menu_get_active_trail();
$menuParent = drupal_html_class($menuParent[1]['link_title']);
$variables['classes_array'][] = $menuParent;

As I said, it works, the backgrounds display correctly, but the error is with the line:

$menuParent = drupal_html_class($menuParent[1]['link_title']);

This is perplexing because the code works and [1] is populated with a host of values, which I can see using:

print_r ($menuParent[1]);

print_r returns:

Array
(
    [menu_name] => main-menu
    [mlid] => 298
    [plid] => 0
    [link_path] => node/1
    [router_path] => node/%
    [link_title] => Motion Pictures
    [options] => Array
        (
        )

    [module] => menu
    [hidden] => 0
    [external] => 0
    [has_children] => 1
    [expanded] => 0
    [weight] => -49
    [depth] => 1
    [customized] => 1
    [p1] => 298
    [p2] => 0
    [p3] => 0
    [p4] => 0
    [p5] => 0
    [p6] => 0
    [p7] => 0
    [p8] => 0
    [p9] => 0
    [updated] => 0
    [load_functions] => a:1:{i:1;s:9:"node_load";}
    [to_arg_functions] => 
    [access_callback] => node_access
    [access_arguments] => a:2:{i:0;s:4:"view";i:1;i:1;}
    [page_callback] => node_page_view
    [page_arguments] => a:1:{i:0;i:1;}
    [delivery_callback] => 
    [tab_parent] => 
    [tab_root] => node/%
    [title] => Motion Pictures
    [title_callback] => node_page_title
    [title_arguments] => a:1:{i:0;i:1;}
    [theme_callback] => 
    [theme_arguments] => a:0:{}
    [type] => 6
    [description] => 
    [in_active_trail] => 1
    [access] => 1
    [href] => node/1
    [localized_options] => Array
        (
        )

I'm totally perplexed. What am I missing?

Comments

nevets’s picture

Two things

Drupal does add a class by default to the body tag that reflects the page.

And this code

$menuParent = drupal_html_class($menuParent[1]['link_title']);

assumes that there is always a $menuParent[1].

What happens if you change it to something like

if ( empty($menuParent[1]) ) {
  return;
}
$menuParent = drupal_html_class($menuParent[1]['link_title']);
drw2013’s picture

That did the trick, thanks!

I saw that Drupal adds the node id as a body class, but given the number of child pages I anticipate, I didn't want to have to specify a background for each node in CSS, and I think this is more elegant.

Thanks again!