You are here

public function CountryStateWidget::getStates in Country, State and City Fields 8

1 call to CountryStateWidget::getStates()
CountryStateWidget::formElement in src/Plugin/Field/FieldWidget/CountryStateWidget.php
Returns the form for a single field widget.

File

src/Plugin/Field/FieldWidget/CountryStateWidget.php, line 115

Class

CountryStateWidget
Plugin implementation of the 'country_state_widget' widget.

Namespace

Drupal\country_state_city\Plugin\Field\FieldWidget

Code

public function getStates($country_id) {
  if ($country_id) {
    $query = $this->entityTypeManager
      ->getStorage('statelist')
      ->getQuery()
      ->condition('country_id', $country_id)
      ->sort('name', 'asc');
    $ids = $query
      ->execute();
    $states = [];
    if (count($ids) == 1) {
      $result = $this->entityTypeManager
        ->getStorage('statelist')
        ->load(key($ids));
      $states[$result
        ->id()] = $result
        ->getName();
    }
    elseif (count($ids) > 1) {
      $results = $this->entityTypeManager
        ->getStorage('statelist')
        ->loadMultiple($ids);
      foreach ($results as $result) {
        $states[$result
          ->id()] = $result
          ->getName();
      }
    }
    return $states;
  }
}