1

I'm experimenting with creating a custom module in Drupal 8. I have created a module that has some custom database tables. One of these tables, "mymodule_tickets" gets populated via admin forms that I have created within the module.

On the public side of the website, I have another custom page setup ('/booking'), which displays a form containing the available 'tickets'. For the mostpart, this works really well, but I am having some trouble understanding caching.

The '/booking' page uses the drupal form api to create a 'number' field for each available ticket. The '#title' of each form field is the name of the ticket as setup in the admin area. When anonymous users view the /booking page, the titles of these form fields cache. If I change the title of the ticket in my admin area, this does not get reflected on the public site for anonymous users.

My first attempt at remedying this was to add this when building the form:

$form['#cache']['max-age'] = 0;

But unfortunately this did not make any difference. Changes to the titles of form elements were still not reflected to the user.

In the end I had to add the following to my routing file:

  options:
    no_cache: TRUE

While this did work and stopped the form titles from caching, it feels like a very heavy-handed way to fix the problem. To me the correct solution would be to cache these pages for anonymous users, but to correctly invalidate the cache after making changes in the admin area.

Are there any guides or code snippets or articles about how to do this? From searching the web I haven't been able to find any relevant information or examples.

3

In your page controller for /bookings, set a cache tag in the build array:

$build['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];

Or since it's a form:

$form['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];

Then when you submit the admin form that has the settings for the page, invalidate the tag:

Cache::invalidateTags(['booking_page_settings']);

You can also add to your cache tags the nodes that display on your booking page, such as 'node:123', or you can add 'node_list' to invalidate the caching when any node is updated.

Your Answer

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

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