You are here

public function LearningPathMembershipController::findUsersInGroupAutocomplete in Opigno Learning path 8

Same name and namespace in other branches
  1. 3.x src/Controller/LearningPathMembershipController.php \Drupal\opigno_learning_path\Controller\LearningPathMembershipController::findUsersInGroupAutocomplete()

Returns users of current group for the autocompletion.

Return value

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

1 string reference to 'LearningPathMembershipController::findUsersInGroupAutocomplete'
opigno_learning_path.routing.yml in ./opigno_learning_path.routing.yml
opigno_learning_path.routing.yml

File

src/Controller/LearningPathMembershipController.php, line 244

Class

LearningPathMembershipController
Controller for the actions related to LP membership.

Namespace

Drupal\opigno_learning_path\Controller

Code

public function findUsersInGroupAutocomplete() {
  $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');

    // 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);

    /** @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.
      if ($curr_group
        ->getMember($user) === FALSE) {
        continue;
      }
      $matches[] = [
        'value' => "{$name} ({$id})",
        'label' => $name,
        'id' => $id,
      ];
    }
  }
  return new JsonResponse($matches);
}