You are here

public function CountryFlagAutocompleteController::autocomplete in Flags 8

Returns response for the country name autocompletion.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The current request object containing the search string.

Return value

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

Overrides CountryAutocompleteController::autocomplete

1 string reference to 'CountryFlagAutocompleteController::autocomplete'
flags_country.routing.yml in flags_country/flags_country.routing.yml
flags_country/flags_country.routing.yml

File

flags_country/src/Controller/CountryFlagAutocompleteController.php, line 24

Class

CountryFlagAutocompleteController
Returns autocomplete responses for countries.

Namespace

Drupal\flags_country\Controller

Code

public function autocomplete(Request $request, $entity_type, $bundle, $field_name) {

  /** @var \Drupal\Core\Render\Renderer $renderer */
  $renderer = \Drupal::service('renderer');
  $matches = array();
  $string = $request->query
    ->get('q');
  if ($string) {
    $field_definition = FieldConfig::loadByName($entity_type, $bundle, $field_name);
    $countries = \Drupal::service('country.field.manager')
      ->getSelectableCountries($field_definition);
    foreach ($countries as $iso2 => $country) {
      if (strpos(mb_strtolower($country), mb_strtolower($string)) !== FALSE) {
        $label = array(
          'country' => array(
            '#markup' => $country,
          ),
          'flag' => array(
            '#theme' => 'flags',
            '#code' => strtolower($iso2),
            '#source' => 'country',
          ),
        );
        $matches[] = array(
          'value' => $country,
          'label' => $renderer
            ->render($label),
        );
      }
    }
  }
  return new JsonResponse($matches);
}