You are here

drupalplanet

Hiding view records based on the value of a new field

Submitted by paulbooker on Tue, 12/16/2014 - 12:36
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();
  
  }		
}

Pages

Subscribe to RSS - drupalplanet