1

In Drupal 7, we are using the following code.

$field = field_info_field('field_name'); $allowed_values = list_allowed_values($field); 

What can we use in Drupal 8?

3 Answers 3

8

Drupal 8.9.x still has the options_allowed_values() (a function implemented in the Options module). If the field uses a selection, check box, or a radio button widget, you could use the following code.

$field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('entity', 'bundle'); if (isset($field_definitions['field'])) { $allowed_options = options_allowed_values($field_definitions['field']->getFieldStorageDefinition()); } 

Replace 'entity' with the entity type ID (for example, 'node' for nodes), 'bundle' with the bundle machine name (for example, 'article' for Article nodes), and 'field' with the field machine name.

Keep in mind that this code requires the Options module; the module using the code I shown should declare its dependency from it.

Using options_allowed_values() has the benefit that, if the field has a function returning the allowed values, that function is called. The following is the code used by options_allowed_values() to achieve that.

if (!isset($allowed_values[$cache_id])) { $function = $definition->getSetting('allowed_values_function'); $cacheable = TRUE; if (!empty($function)) { $values = $function($definition, $entity, $cacheable); } else { $values = $definition->getSetting('allowed_values'); } if ($cacheable) { $allowed_values[$cache_id] = $values; } else { return $values; } } 

Using options_allowed_values() also allows to cache the allowed values. In this way, calling options_allowed_values() for the same field (and same entity type) multiple times has a minimal impact on performance.

options_allowed_values() is still defined in Drupal 9.x, Drupal 10.x, and Drupal 11.x.

4

To get list of allowed values of field of select list try with:

 $options_array = []; $field_name = 'field_name'; $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('custom_entity_name', 'bundle'); if (isset($definitions[$field_name])) { $options_array = $definitions[$field_name]->getSetting('allowed_values'); } 
2

Try directly from field:

 $allowedVals = $entity->get('field_name')->getSettings()['allowed_values']; 
2
  • 2
    I believe we can say $entity->get('field_name')->getSetting('allowed_values') (Drupal 9) Commented Mar 22, 2023 at 16:38
  • (Drupal 9): If entity is loaded, then $entity->get('field_name')->getFieldDefinition()->getSetting('allowed_values'); Commented May 14, 2024 at 12:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.