I have created a new view mode for the user entity. I want to create a template for that view mode. With node entities, this is easy enough, but I can't figure out how to do it with user entities.

For nodes, I do something like...

drupal_render(node_view($node, 'my view mode'))

...along with...

function mytheme_preprocess_node(&$vars) {
  $node = $vars['node'];
  $vars['theme_hook_suggestions'][] = 'node__' . $node->type . '__' . $vars['view_mode']; 
}

I can then use a template in my theme like... node--<type>--<view_mode>.tpl.php

There doesn't seem to be a hook_preprocess_user function, though, so I'm not sure where to add my theme_hook_suggestions so I can have a template like user--<view_mode>.tpl.php

A little more context, if it's needed: I am building a list of users (matching my query conditions) in a custom block. I then will loop through the results, building a list like...

foreach ($result['user'] as $row) { 
    $uid = (int)$row->uid;
    $user = user_load($uid);
    $key = $user->created . '-' . $uid;
    $users[$key] = drupal_render(user_view($user, 'my view mode'));
  }

...and then a little later in the code I theme the list with theme_item_list. This has worked great for node entities and comment entities. But the api seems to be different for user entities.

Thank you

Comments

arnoldbird’s picture

I went looking for this again today. There is apparently no hook_preprocess_user(), though there is a hook_preprocess_user_profile().

However, theme_hook_suggestions set in hook_preprocess_user_profile() are not respected by Drupal's theme system. If I dump $vars['theme_hook_suggestions'], I get...

array(1) { [0]=> string(10) "user__list" }

...yet my user--list.tpl.php template is not invoked. Instead, Drupal invokes block.tpl.php.

Drupal's API for working with entities is still inconsistent as of Drupal 7.

havran’s picture

For me work this:

/**
 * Implements hook_entity_info_alter().
 *
 * The first attribute in the array defines an arbitrary label for the view mode machine name.
 * 'custom settings' => TRUE displays the view mode as a default at the top of the display modes settings screen
 */
function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['user']['view modes'] += array(
    'search_result' => array(
      'label' => t('Search result'),
      'custom settings' => TRUE,
    ),
  );
}

/**
 * Preprocess user profile.
 *
 * @param array $vars
 */
function mymodule_preprocess_user_profile(&$vars) {
  if ($vars['elements']['#view_mode'] == 'search_result') {
    $vars['theme_hook_suggestions'][] = 'user_profile__search_result';
  }
}

I use this for alternate results in Search API search users.

--
My site - Svoji.SK
My first Drupal site - http://www.enigma.sk/