You are here

function user_reference_field_prepare_view in References 7.2

Implements hook_field_prepare_view().

File

user_reference/user_reference.module, line 219
Defines a field type for referencing a user from a node.

Code

function user_reference_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
  $checked_ids =& drupal_static(__FUNCTION__, array());

  // Set an 'access' property on each item (TRUE if the user exists).
  // Extract ids to check.
  $ids = array();
  foreach ($items as $id => $entity_items) {
    foreach ($entity_items as $delta => $item) {
      if (is_array($item)) {

        // Default to 'not accessible'.
        $items[$id][$delta]['access'] = FALSE;
        if (!empty($item['uid']) && is_numeric($item['uid'])) {
          $ids[$item['uid']] = $item['uid'];
        }
      }
    }
  }
  if ($ids) {

    // Load information about ids that we haven't already loaded during this
    // page request.
    $ids_to_check = array_diff($ids, array_keys($checked_ids));
    if (!empty($ids_to_check)) {
      $query = db_select('users', 'u')
        ->addMetaData('id', 'user_reference_field_prepare_view')
        ->addMetaData('field', $field)
        ->fields('u', array(
        'uid',
      ))
        ->condition('u.uid', $ids_to_check, 'IN');
      $accessible_ids = $query
        ->execute()
        ->fetchAllAssoc('uid');

      // Populate our static list so that we do not query on those ids again.
      foreach ($ids_to_check as $id) {
        $checked_ids[$id] = isset($accessible_ids[$id]);
      }
    }
    foreach ($items as $id => $entity_items) {
      foreach ($entity_items as $delta => $item) {
        if (is_array($item) && !empty($item['uid']) && !empty($checked_ids[$item['uid']])) {
          $items[$id][$delta]['access'] = TRUE;
        }
      }
    }
  }
}