Get a list of fields by type

Getting needed list of a specific field type might be used in Drupal's config form or for any other abstract functionality.
Bellow is an example of how to get fields of type `entity_reference` and if needed, can be limited to a specific target type.


$entityTypeManager = \Drupal::entityTypeManager();
$entityRefFields = $entityTypeManager->getStorage('field_storage_config')
  ->loadByProperties([
    'type' => 'entity_reference',
    // Limit by a specific reference type.
    // 'settings' => ['target_type' => 'node'],
  ]);
$options = [];
foreach ($entityRefFields as $entityRefField) {
  $fieldName = $entityRefField->getName();
  $options[$fieldName] = $fieldName;
}

 

For convenience we can put above in a function


function getFieldsByTypeAsOptions(string $type, ?array $settings = NULL): array {
  $properties = ['type' => $type];
  if ($settings) {
    $properties = ['settings' => $settings];
  }
  $entityTypeManager = \Drupal::entityTypeManager();
  $entityRefFields = $entityTypeManager
    ->getStorage('field_storage_config')
    ->loadByProperties($properties);
  $options = ['' => '- Select -'];
  foreach ($entityRefFields as $entityRefField) {
    $fieldName = $entityRefField->getName();
    $options[$fieldName] = $fieldName;
  }
  return $options;
}

 

Usage example


// Entity Reference Fields referencing to Node entities.
$this->getFieldsByTypeAsOptions('entity_reference', ['target_type' => 'node']);

// Entity Reference Fields referencing to Taxonomy Term entities.
$this->getFieldsByTypeAsOptions('entity_reference', ['target_type' => 'taxonomy_term']);

// Boolean Fields.
$this->getFieldsByTypeAsOptions('boolean');

// Datetime Range Fields.
$this->getFieldsByTypeAsOptions('daterange');
********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************