First impression with views 2 hooks, its amazing

You, DrupalDrupal views
Back

Recently I could work with great two hooks in views2 which are

hook_views_query_alter() I used this because I just want to add new table join with the current one and add a where condition.

hook_views_pre_render() I use this to remove some values from display.

Problem : I wanted to add user_reference cck field to my content type to assign some users with a node. First I created a new content type and added user_referance field in to it. But for me there should be a restriction that is if we assign one user to a node then that users should not be able to add to another node. Currently user_referance doesn't have such a facility so I have to override the hook_views_pre_render() and remove the user values where they already assigned.

How did I solve:

<?php
/**
* Implements hook_views_pre_render().
*/
function alter_user_reference_views_pre_render(&$view, &$output, &$cache) {
  // get the node id it its there
  $nid = arg(1);
  if (is_numeric($nid)) // get the userids without related to this node
    $result = db_query('SELECT field_academy_members_uid FROM {content_field_academy_members} WHERE nid != %d', $nid);
  else
    $result = db_query('SELECT field_academy_members_uid FROM {content_field_academy_members}');
  $users = array();
  while ($uid = db_result($result)) {
  // put all in to an array
    $users[] = $uid;
  }
  if ($view->name == 'users_who_doesnt_have_commission') {
    $results = array();
    // the values exists in $view->result so we can override it
    foreach ($view->result as $key => $user) {
      if (in_array($user->uid, $users))
        unset($view->result[$key]);
      else
        $results[] = $user;
    }
    // override with new results
    $view->result = $results;
  }
}
?>
© Heshan Wanigasooriya.RSS

🍪 This site does not track you.