Modifying module configuration in update hook after enabling

When dealing with configuration updates with hook_update_N(), there is one thing to look out for related to enabling modules programmatically.

Lets say you have similar hook:

File: custom_module/custom_module.install
function custom_module_update_9001() { \Drupal::service('module_installer')->install(['my_module']); \Drupal::configFactory()->getEditable('my_module.settings') ->set('parameter', 'value') ->save(); }

This actually may not work as expected - when configFactory is loading that configuration, it might not be aware of my_module.settings, because enabling module does not clear any caches. This also means that it will create a new configuration with the values you set discarding all others that are coming from module itself.

The correct update hook should like this:

File: custom_module/custom_module.install
function custom_module_update_9001() { \Drupal::service('module_installer')->install(['my_module']); // Clear caches before modifying configuration in previously enabled module. drupal_flush_all_caches(); \Drupal::configFactory()->getEditable('my_module.settings') ->set('parameter', 'value') ->save(); }

Clearing caches will make the configFactory aware of the new configuration and it shouldn't cause any issues anymore. It took a while to discover it.

Buy Me a Coffee at ko-fi.com

Add new comment