You are here

public function LearningPathMembershipController::addUserToClassAutocomplete in Opigno Learning path 3.x

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

Returns response for the autocompletion.

Parameters

\Drupal\group\Entity\Group $group: Group.

Return value

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

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

File

src/Controller/LearningPathMembershipController.php, line 221

Class

LearningPathMembershipController
Controller for the actions related to LP membership.

Namespace

Drupal\opigno_learning_path\Controller

Code

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

    // Find users by email or name.
    $query = \Drupal::entityQuery('user')
      ->condition('uid', 0, '<>')
      ->condition('name', $like_string, 'LIKE')
      ->sort('name')
      ->range(0, 20);
    $uids = $query
      ->execute();
    $count = count($uids);
    if ($count < 20) {
      $range = 20 - $count;
      $query = \Drupal::entityQuery('user')
        ->condition('uid', 0, '<>')
        ->condition('mail', $like_string, 'LIKE')
        ->sort('name')
        ->range(0, $range);
      $uids = array_merge($uids, $query
        ->execute());
    }
    $users = User::loadMultiple($uids);

    /** @var \Drupal\user\Entity\User $user */
    foreach ($users as $user) {
      $id = $user
        ->id();
      $name = $user
        ->getDisplayName();
      $matches[] = [
        'value' => "{$name} ({$id})",
        'label' => "{$name} ({$id})",
        'type' => 'user',
        'id' => 'user_' . $id,
      ];
    }
  }
  return new JsonResponse($matches);
}