0

This question has been asked before, but the regularly accepted solution is not working for me. I want the node form to be rebuilt on every page refresh. I have added an implementation of hook_form_BASE_FORM_ID_alter(), like so:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function my_module_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#cache']['max-age'] = 0;
}

The array inside $form['#cache'] looks like this:

contexts = [
  languages:language_interface
  user.roles:authenticated
]
tags = [
  config:core.entity_form_display.node.article.default
  node:123
]
max-age = 0

...but the form remains cached?

Ideally, I would like to clear the node form's cache only when a new node, of a particular type, is created. When such a node is created, a new token is also generated - and it is the token tree that I want to become updated in the node form because I am adding a tokens link tree to the base of my body field widget.

$form['body']['tokens_tree'] = array(
  '#theme' => 'token_tree_link',
  '#token_types' => ['my_tokens'],
  '#global_types' => FALSE,
);

I'm assuming that invalidating the cache of the node form will achieve my goal. Certainly, doing drush cr does the job.

  • Have you tried just overwriting the whole #cache array key? $form['#cache'] = ['max-age' => 0];. You don't need the contexts and tags etc since it's not cacheable anyway. – Beebee Jun 25 '18 at 8:26
  • For the second part, I think hook_entity_insert is probably too late for what you're trying to do, so best to do in the alter. What you can do to grab the bundle is $type = $form['#node']->type; since you're altering a node_form #node should always be set. – Beebee Jun 25 '18 at 8:33
  • 1
    Not a direct answer to the Q, but generally speaking I think rather than trying to clear the cache yourself, or prevent it altogether, ideally you'd use a cache tag. You say you'd like to clear the cache when a new node of a specific type is created: there isn't a tag for specific bundles (yet) but you could use node_list which is used for node listings. To be more granular you could create a custom cache tag. – Andy Jun 25 '18 at 9:34
  • So, I removed my node type and created a custom content entity (my_custom_entity) to replace it. I then added $form['#cache']['tags'][] = 'my_custom_entity_list'; to my node form alter, but no luck: my node form is not rebuilding when I update, delete or create a custom entity. – 24ma13wg Jun 25 '18 at 14:21
  • On inspecting the X-Drupal-Cache-Tags headers I can see my_custom_entity_list and node:123, but even when I edit node/123 the form does not appear to fully rebuild, not in the way it does if I do drush cr. – 24ma13wg Jun 25 '18 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.