5

I have a simple configuration parameter for a custom module. I use this parameter to decide how to render a field using a custom render element:

class Jmol extends RenderElement {

/**
 * Define the available options for our new render element.
 */
public function getInfo() {
$class = get_class($this);

// Produce the default settings for our render element.
return [
  '#pre_render' => [
    [$class, 'preRenderJmol'],
  ],
  '#version' => NULL,
  '#theme' => NULL,
  '#id' => 'mydiv',
  '#info' => [],
  '#attached' => [
    'library' => [],
  ],
];
}

public static function preRenderJmol($element) {

// Examine the config file to see which library version to use.
$config = \Drupal::config('jmol.settings');
$version = $config->get('version');
// Look at the element to see which version the user would like to use.
// They may have changed it from the default.
if ($element['#version'] != NULL) {
  $version = $element['#version'];
}

// The twig template to use.
$theme = "";

// Add the correct library to any the user has already provided.
$library = $element['#attached']['library'];
if ($version == 'full') {
  $theme = 'jmol_full_template';
  $library[] = 'jmol/jmol_full';
}
elseif ($version == 'lite') {
  $theme = 'jmol_lite_template';
  $library[] = 'jmol/jmol_lite';
}

// Only add the theme if the user has not specified one.
if ($element['#theme'] == NULL) {
  $element['#theme'] = $theme;
}

// Add the info array to drupalSetting so the JS can access it.
$id = $element['#id'];
$drupalsettings['jmol'][$id] = [
  'info' => $element['#info'],
];

$element['#attached'] = [
  'drupalSettings' => $drupalsettings,
  'library' => $library,
];

return $element;
}

If I visit the module settings page and change the value of the "version" parameter, my module continues to behave the same until I clear the cache.

The submit portion of my configuration form is:

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('jmol.settings');
  $config->set('version', $form_state->getValue('jmol_version'))
  ->save();

  parent::submitForm($form, $form_state);
}

Is there something else my submitForm function needs to do, or is there a different way I need to be reading the config parameter?

1 Answer 1

8

You need to set the cache tag to invalidate your output if the configuration changes. That's as easy as adding this to your render array:

$element['#cache']['tags'] = $config->getCacheTags();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.