How do I programmatically update the allowed values of a list field? I have created a field_time_zone field for the Article content type.
I want to set the allowed values for that field to the values returned from system_time_zones().
For this, I implemented hook_form_alter() using the following code.
$zones = system_time_zones();
$entityManager = \Drupal::service('entity_field.manager');
$fields = $entityManager-&gt;getFieldStorageDefinitions('node', 'local_market');
$options = options_allowed_values($fields['field_time_zone']);

if(empty($options)) {
$options =  $zones;
$form['field_time_zone']['widget']['#options'] = $options;
}

The code adds the desired values, but the node cannot be saved, as it throws the following error.

The value you selected is not a valid choice.

How can I set the allowed values for a text (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: {  }