Score:1

How to invalidate config or service cache

sa flag

I have a service wich is loading a config at construct time:

class MyService {
  public function __construct(ConfigFactoryInterface $config_factory) {
    $config = $config_factory->get('my.config');
    ...
  }
...
}

There is a config form to fill in the my.config's values.

In the submit function of this form, I obviously save the config but after that, I would like to use MyService. Unfortunately, the config loaded by MyService doesn't contains the last changes encoded in the config form.

Not sure it is useful to know, but MyService is also loaded in buildForm()

Here is the submit function in which I am trying to invalidate my.config

public function submitForm(array &$form, FormStateInterface $form_state) {
  ...
  $config->save();
  \Drupal::cache()->invalidate('my.config');
  \Drupal::cache()->invalidate('my.service');
  $my_service = Drupal::service('my.service');
  $my_service->useMyService(); // it will use the old values
}
4uk4 avatar
cn flag
Normally, after submitting a form, you redirect to a new page with all services loaded from scratch. It's more likely this is related to render caching where you need to include the cache tag of the config object. See https://www.drupal.org/docs/drupal-apis/render-api/cacheability-of-render-arrays
Baud avatar
sa flag
I do not render anything in `useMyService()`... I don't know how to use `addCacheableDependency` as I do not have a renderer.
4uk4 avatar
cn flag
This is a very unusual use case then. Normally the form handles the editable config object instantiated with the form object and the service the immutable version of the config object. If you really need to update the service within the submit request your service needs a setter method for the config object. Reset the config object in the config factory and load it again to set it in the service.
Baud avatar
sa flag
Thank you for the idea. I will go with 2 steps: submitting the form will redirect to another form which will run the service.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.