Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Hiding view records based on the value of a new field

Parent Feed: 
function mymodule_views_query_alter(&$view, &$query) {

  global $user;
        
  if (($view->name === 'coaches') || ($view->name === 'trainers')) { 
   
    if (!in_array('trainer', $user->roles) && !in_array('admin', $user->roles)) {
  
      $view->query->fields['field_data_field_profile_hidden'] = array(
        'field' => 'field_profile_hidden_value',
        'table' => 'field_data_field_profile_hidden',
        'alias' => 'field_data_field_profile_hidden'
      );
      
      $join = new views_join;
      $join->table ='field_data_field_profile_hidden';
      $join->left_table = 'users';
      $join->left_field = 'uid';
      $join->field = 'entity_id';
      $join->extra = array(
        0 => array('field' => 'entity_type', 'value' => 'user'),
      );
      $join->type = "LEFT";
      $join->extra_type = 'AND';
      $join->adjusted = 'TRUE';
      
      // add the join
      $view->query->table_queue['field_data_field_profile_hidden'] = array(
        'table' => 'field_data_field_profile_hidden',
        'num' => 1,
        'alias' => 'field_data_field_profile_hidden',
        'join' => $join,
        'relationship' => 'users'
      );
  
      $view->query->tables['node']['field_data_field_profile_hidden'] = array(
        'count' => 1,
        'alias' => 'field_data_field_profile_hidden'
      );
  
      $view->query->where[2]['conditions'][] = array(
        'field' => 'field_profile_hidden_value',
        'value' => 0,
        'operator' => '='
      );
  
    }
  }
}
/**
 * Implements hook_update_N().
 */
function mymodule_update_7001(&$sandbox) {

  $uids = db_select('users', 'u')
    ->fields('u', array('uid'))
                ->execute()
                ->fetchCol();
                
  foreach ($uids as $uid) {
  
    db_insert('field_data_field_profile_hidden')
      ->fields(array(
        'entity_type' => 'user',
        'bundle' => 'user',
        'entity_id' => $uid,
        'revision_id' => $uid,
        'language' => 'und',
        'delta' => 0,
        'field_profile_hidden_value' => 0,
    ))
    ->execute();
  
  }             
}
Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web