Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to update an existing drupal 8 site setting field with a hook update
* @file
* Install, update and uninstall functions for the YOUR_MODULE_NAME module.
* Implements hook_update_N().
* Update field_example on the my_example_setting site
* setting to have all the term_example taxonomy terms selected.
function YOUR_MODULE_NAME_update_8001(&$sandbox) {
// Query the my_example_setting site settings to get their id's.
$my_example_setting_ids = \Drupal::entityQuery('site_setting_entity')
->condition('type', 'my_example_setting')
// Load the application cta column entities using their id's.
$my_example_setting_entity = \Drupal::entityTypeManager()
// Load the term_example taxonomy terms and put them into $terms
// data array, which holds the term id's.
$vid = 'term_example';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
$terms_data = [];
foreach ($terms as $term) {
$terms_data[] = [
'target_id' => $term->tid,
// For each my_example_setting, set the field data for
// field_example to equal the $term_data array and save it.
foreach ($my_example_setting_entity as $entity) {
$entity->set('field_example', $terms_data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment