You are here

public function MoxtraMembershipController::addToGroupWorkspaceUserAutocomplete in Opigno Moxtra 8

Same name and namespace in other branches
  1. 3.x src/Controller/MoxtraMembershipController.php \Drupal\opigno_moxtra\Controller\MoxtraMembershipController::addToGroupWorkspaceUserAutocomplete()

Returns users of current group for the autocompletion.

Return value

\Symfony\Component\HttpFoundation\JsonResponse A JSON response containing the autocomplete suggestions.

File

src/Controller/MoxtraMembershipController.php, line 58

Class

MoxtraMembershipController
Controller for the actions related to moxtra membership.

Namespace

Drupal\opigno_moxtra\Controller

Code

public function addToGroupWorkspaceUserAutocomplete() {
  $matches = [];
  $string = \Drupal::request()->query
    ->get('q');
  if ($string) {
    $like_string = '%' . $this->connection
      ->escapeLike($string) . '%';

    /** @var \Drupal\group\Entity\Group $curr_group */
    $curr_group = \Drupal::routeMatch()
      ->getParameter('group');
    $workspace = \Drupal::routeMatch()
      ->getParameter('workspace');

    // Find users by email or name.
    $query = \Drupal::entityQuery('user')
      ->condition('uid', 0, '<>');
    $cond_group = $query
      ->orConditionGroup()
      ->condition('mail', $like_string, 'LIKE')
      ->condition('name', $like_string, 'LIKE');
    $query = $query
      ->condition($cond_group)
      ->sort('name');
    $uids = $query
      ->execute();
    $users = User::loadMultiple($uids);
    $current_members = $workspace
      ->getMembersIds();

    /** @var \Drupal\user\Entity\User $user */
    foreach ($users as $user) {
      $id = $user
        ->id();
      $name = $user
        ->getDisplayName();

      // Remove users that are not members of current group
      // or already in workspace.
      if ($curr_group
        ->getMember($user) === FALSE || in_array($id, $current_members) || !_opigno_moxtra_is_user_enabled($user)) {
        continue;
      }
      $matches[] = [
        'value' => "{$name} ({$id})",
        'label' => $name,
        'id' => $id,
      ];
    }
  }
  return new JsonResponse($matches);
}