CountryAutocompleteController.php in Country 8
File
src/Controller/CountryAutocompleteController.php
View source
<?php
namespace Drupal\country\Controller;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Locale\CountryManagerInterface;
use Drupal\country\CountryFieldManager;
use Drupal\field\Entity\FieldConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class CountryAutocompleteController implements ContainerInjectionInterface {
protected $countryManager;
protected $countryFieldManager;
public function __construct(CountryManagerInterface $country_manager, CountryFieldManager $country_field_manager) {
$this->countryManager = $country_manager;
$this->countryFieldManager = $country_field_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('country_manager'), $container
->get('country.field.manager'));
}
public function autocomplete(Request $request, $entity_type, $bundle, $field_name) {
$matches = [];
$string = $request->query
->get('q');
if ($string) {
if ($bundle == 'global') {
$countries = $this->countryManager
->getList();
}
else {
$field_definition = FieldConfig::loadByName($entity_type, $bundle, $field_name);
$countries = $this->countryFieldManager
->getSelectableCountries($field_definition);
}
foreach ($countries as $iso2 => $country) {
if (strpos(mb_strtolower($country), mb_strtolower($string)) !== FALSE) {
$matches[] = [
'value' => $country,
'label' => $country,
];
}
}
}
return new JsonResponse($matches);
}
}