How to clear cache for config entity after making changes? We have a custom form mymoduleForm that has mymodule.settings which stores some values that we need to run some logic when calling mymodule_preprocess_node() hook. The form just has a text area where we insert URIs and use that in the mymodule_preprocess_node hook to perform some action. 

We can store the values in a Config entity as expected (see below). When we make changes to the Config entity, we want to clear cache for the config entity as well. How can we clear the Config Entity's Cache after making changes?

Goal:


When there are updates to the Config entity, clear the cache for the entity so that the latest entity is used in mymodule_preprocess_node hook. 


Issue:


When we make changes to the Config entity using the custom form, the logic that we need to run is not running with the latest settings. 


What we have tried:


Tried adding addCacheableDependency($form, $config);  to the buildForm(), but it is not working. 


mymoduleForm.php

class mymoduleForm extends ConfigFormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!$this-&gt;entity-&gt;isNew()) {
        \Drupal::service('renderer')-&gt;addCacheableDependency($form, $this-&gt;entity);
      }

    $config = $this-&gt;config('mymodule.settings');

    $form['some_field'] = [
      '#type' =&gt; 'textarea',
      '#title' =&gt; $this-&gt;t('Some field title'),
      '#description' =&gt; $this-&gt;t('some description'),
      '#default_value' =&gt; $config-&gt;get('some_field'),
    ];

    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &amp;$form, FormStateInterface $form_state) {
    $this-&gt;config('mymodule.settings'),
      -&gt;set('some_field', $form_state-&gt;getValue('some_fields'))
      -&gt;save();
  }
}


mymodule_preprocess_node

function mymodule_preprocess_node(&amp;$variables) {
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config-&gt;get('some_field');

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}
Yes, you have to add the cacheable dependencies of the config object, not only to the form, but also to the render array in preprocess, so that the rendered output gets the correct cache data:

function mymodule_preprocess_node(&amp;$variables) {
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config-&gt;get('some_field');
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')-&gt;addCacheableDependency($variables, $config);

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}