You are here

function opigno_calendar_views_query_alter in Opigno calendar event 8

Same name and namespace in other branches
  1. 3.x opigno_calendar_event.module \opigno_calendar_views_query_alter()

Implements hook_views_query_alter().

Parameters

\Drupal\views\ViewExecutable $view: View object.

\Drupal\views\Plugin\views\query\QueryPluginBase $query: Query object.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

./opigno_calendar_event.module, line 180
Main file for the "Calendar event" module.

Code

function opigno_calendar_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view
    ->id() === 'opigno_calendar') {
    $current_user = \Drupal::currentUser()
      ->id();
    $table_mapping = \Drupal::entityTypeManager()
      ->getStorage('opigno_calendar_event')
      ->getTableMapping();
    $table = $table_mapping
      ->getFieldTableName('field_calendar_event_members');
    $definition = [
      'table' => $table,
      'field' => 'entity_id',
      'left_table' => 'opigno_calendar_event_field_data',
      'left_field' => 'id',
    ];
    $join = Drupal::service('plugin.manager.views.join')
      ->createInstance('standard', $definition);
    $query
      ->addRelationship($table, $join, $table);

    // Events of a current user OR without members.
    // Authenticated user will see only own.
    // But roles that has access "View any calendar event entities"
    // will see own and without members.
    $query->where[] = [
      'conditions' => [
        [
          'field' => $table . '.field_calendar_event_members_target_id',
          'value' => NULL,
          'operator' => 'IS NULL',
        ],
        [
          'field' => $table . '.field_calendar_event_members_target_id',
          'value' => $current_user,
          'operator' => '=',
        ],
      ],
      'type' => 'OR',
    ];
  }
}