Skip to content

Instantly share code, notes, and snippets.

@lincoln-chawora
Last active January 10, 2020 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lincoln-chawora/4ed1e407ba83d2e6f1bb5acbc75a63d5 to your computer and use it in GitHub Desktop.
Save lincoln-chawora/4ed1e407ba83d2e6f1bb5acbc75a63d5 to your computer and use it in GitHub Desktop.
How change the allowed values of a select list or radio field dynamically in drupal 8
settings:
allowed_values: { }
# Add the line below to your file as it will reference the function you'll create in your .module file
allowed_values_function: example_allowed_values_function
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Set dynamic allowed values for the content author field(s).
*
* @param \Drupal\field\Entity\FieldStorageConfig $definition
* The field definition.
* @param \Drupal\Core\Entity\ContentEntityInterface|null $entity
* The entity being created if applicable.
* @param bool $cacheable
* Boolean indicating if the results are cacheable.
*
* @return array
* An array of possible key and value options.
*
* @see options_allowed_values()
*/
function example_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable) {
$options = [
'current_user' => 'Current user',
'content_creator' => 'Content user'
];
return $options;
}
@lincoln-chawora
Copy link
Author

lincoln-chawora commented Dec 19, 2019

Some notes:

  1. once the field storage file is updated you will need to run drush cim for the changes to come into effect
  2. this code is based on the following article you should read it for further detail: https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment