You are here

public function ILTController::trainerAutocomplete in Opigno Instructor-led Trainings 3.x

Same name and namespace in other branches
  1. 8 src/Controller/ILTController.php \Drupal\opigno_ilt\Controller\ILTController::trainerAutocomplete()

Returns response for the autocompletion.

Parameters

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

Return value

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

1 string reference to 'ILTController::trainerAutocomplete'
opigno_ilt.routing.yml in ./opigno_ilt.routing.yml
opigno_ilt.routing.yml

File

src/Controller/ILTController.php, line 105

Class

ILTController
Class ILTController.

Namespace

Drupal\opigno_ilt\Controller

Code

public function trainerAutocomplete(Group $group) {
  $matches = [];
  $search = \Drupal::request()->query
    ->get('q');
  if (!isset($search)) {
    $search = '';
  }
  if (isset($group)) {
    $training_members = $group
      ->getMembers();
    $training_users = array_map(function ($member) {

      /** @var \Drupal\group\GroupMembership $member */
      return $member
        ->getUser();
    }, $training_members);
    foreach ($training_users as $user) {

      /** @var \Drupal\user\UserInterface $user */
      $id = $user
        ->id();
      $name = $user
        ->getDisplayName();
      $label = $this
        ->t("@name", [
        '@name' => $name,
        '@id' => $id,
      ]);
      $matches[] = [
        'value' => $label,
        'label' => $label,
        'type' => 'user',
        'id' => 'user_' . $id,
        'name' => $name,
      ];
    }
    $search = strtoupper($search);
    $matches = array_filter($matches, function ($match) use ($search) {
      $name = strtoupper($match['name']);
      return strpos($name, $search) !== FALSE;
    });
    usort($matches, function ($match1, $match2) {
      return strcasecmp($match1['name'], $match2['name']);
    });
  }
  return new JsonResponse($matches);
}