drupaldrupal-7user-profilehook-form-alter

Display all nodes for which user appears as a field on that user's profile?


I have a site with a content type "Projects," which has a field "Project Manager" that takes a user. Is there a good way to display all Projects for which a user appears as the Project Manager for that Project on that user's profile?

Update:

Here is what I have so far in user_profile.tpl.php

...
function my_module_user_view($account, $view_mode, $langcode) {

  $my_field = 'field_pm';
  $uid = $account->uid; // The uid of the user being viewed.
  $query = "SELECT entity_id FROM {field_data_{$my_field}} WHERE {$my_field}_target_id = :uid AND bundle='user'";
  $args = array(':uid' => $uid,);
  $result = db_query($query, $args);
  $nids = $result->fetchCol();
  if (count($nids)) {
    $projects = node_load_multiple($nids); // Load all projects where that user is a PM
    foreach ($projects as $project) {
      $account->content['field_pm_projects'][0]['#markup'] = $project->title;
    }
  }
}
?>

<div class="profile"<?php print $attributes; ?>>
 <?php print render($user_profile); ?>
 <?php print $account->content['field_pm_projects']; ?></span>
</div>

Solution

  • The easiest way is to use a EntityFieldQuery to achieve your desired result. Here is how you can do it:

        global $user;
        $query = new EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
                ->entityCondition('bundle', 'projects')
                ->propertyCondition('status', 1)
                ->propertyCondition('uid', $user->uid
                ->fieldCondition('field_<YOUR_CUSTOM_FIELD>', '<COLUMN_NAME>', '<VALUE>', '=')
                ->execute();
    
    if (!empty($result['node'])) {
        $nids = array_keys($result['node']);
        $nodes = node_load_multiple(array_keys($result['node']));
    }
    

    for more information about EntityFieldQuery please follow the link here.. https://www.drupal.org/node/1343708

    Hope this will solve your problem.GL