How to Get the Allowed Values from a List (text) Field in Drupal 8/9


There are times when we need to build custom forms or have custom displays which show all of the allowed field values for a List (text) field. It’s pretty easy when you know what services to hit!

For this example, we’ll assume we’re starting with a more or less fresh Drupal site. Add a field to the Article content type with a label of Category and a machine name of field_category and make it a List (text) field.

Press Save and continue, then let’s add some values to the list. We will specify the keys and values so we can see that we get them both. The keys will be lower-case and the values will have the first letters capitalized.


Field values for easy copy/pasting:

one|One
two|Two
three|Three
four|Four

Press Save field settings, then since we aren’t changing anything on the next form, press Save settings.


Now our Article content type has a new Category field. We want to display those values somewhere. We won’t go through the steps of creating a new module or using something like devel_php here, so you’ll need to get to the point where you’re executing code on your own.

To retrieve the allowed values, we’ll need to use the EntityFieldManager service and then specify the entity type, bundle, and field name that we’re getting the list of values for. Of course, you’ll want to use dependency injection to use the service if you are putting this in a class, form, plugin, or service.

$allowedValues = [];
$entityType = 'node';
$fieldName = 'field_category';
$bundle = 'article';

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($entityType, $bundle);
if (array_key_exists($fieldName, $fields)) {
  /** @var \Drupal\field\Entity\FieldConfig $fieldConfig */
  $fieldConfig = $fields[$fieldName];
  $allowedValues = $fieldConfig->getSetting('allowed_values');
}

This sets $allowedValues to the values we configured on the field. It looks like this:



Array
(
    [one] => One
    [two] => Two
    [three] => Three
    [four] => Four
)

Now you can use this to set options on elements on custom forms or wherever you need to display the allowed values for a list field.



169 views0 comments

Recent Posts

See All