Drupal - How do I programmatically update the allowed values of a list field?
You can't do this in a form alter hook, because the entity field validation will fail.
You have to add a function to the field settings. This is not in the field UI, so you have to export the configuration and change the field in field.storage.node.field_time_zone.yml:
type: list_string
settings:
allowed_values: { }
allowed_values_function: 'mymodule_allowed_values_function'
Reimport the configuration. Then you can implement this function in mymodule.module to set the options dynamically:
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\field\Entity\FieldStorageConfig;
function mymodule_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable) {
$options = [
...
];
return $options;
}
See https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8
For the question added later:
How can I set allowed value options to a field of type text(list) and save it accordingly?
The question originally was what to do with the code which doesn't work in form alter, where you can place it instead.
If you mean with this question you have a static allowed value list, then you can copy and paste the list in the field settings UI and save it:
And now it is stored in the mentioned yaml file of the exported configuration here:
allowed_values: { }
After many hours i finally found solution. I dynamically created options for multi select field and got error message on submit that choosen select in wrong option.
It requires add new options to allowed_values for that field. Here is the solution:
//load your field
$field_purchasers = FieldStorageConfig::loadByName('user', 'field_xx');
//subscribe new options to this field
$field_purchasers->setSetting('allowed_values_function','module_name_allowed_values_function' );
//save configuration
$field_purchasers->save();
In your .module file write in callback function :
function module_name_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable) {
$options = [
1 => 'My new option 1',
2 => 'My new option 2',
3 => 'My new option 3',
];
return $options;
}