Skip to content

Instantly share code, notes, and snippets.

@lincoln-chawora
Created January 10, 2020 18:56
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/e4509547d0ef2a217e5c9f84300b6ce3 to your computer and use it in GitHub Desktop.
Save lincoln-chawora/e4509547d0ef2a217e5c9f84300b6ce3 to your computer and use it in GitHub Desktop.
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')
->execute();
// Load the application cta column entities using their id's.
$my_example_setting_entity = \Drupal::entityTypeManager()
->getStorage('site_setting_entity')
->loadMultiple($application_cta_columns_ids);
// 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);
$entity->save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment