I have a custom module which builds a set of complicated forms, and these forms are built dynamically (the option lists for certain SELECT items, for example, are fetched via an API call). Some of these forms take 14 seconds to load, whereas a simple "static" form takes 2 seconds.

The data behind the dynamic forms does not change often and so I want to cache the render array of the form, so that a complicated form could also load in 2 seconds. A cache life of an hour would be fine, for example.

I have not yet found how do this, or at least what I have tried has not helped the speed.

All forms in question are only available to logged in users, as they are for staff use only.

On /admin/config/development/performance I have "Browser and proxy cache maximum age" set to 1 hour.

  • I think its more practical to cache the options fetched from the API, not the entire form itself. The problem is not the browser cache setting, its probably the API fetching remote data every time the form is loaded.
    – Kevin
    Dec 29, 2022 at 18:02
  • The API is actually local -- it's the CiviCRM API and it's not just one call, it's a few hundred calls for certain forms.
    – Hershel
    Dec 29, 2022 at 18:09
  • Remote or lot, still a lot of work. Especially if those calls use db_select, process tons of items, etc. Once those responses are cached (ready to use like an array of options) this problem will be drastically improved.
    – Kevin
    Dec 30, 2022 at 14:46

1 Answer 1


You can store the data in a cache.

$cid = 'mymodule_example';
$data = NULL;
if ($cache = \Drupal::cache()
  ->get($cid)) {
  $data = $cache->data;
else {
  $data = my_module_complicated_calculation();
    ->set($cid, $data);

foreach ($data as $something) {
  // build render array

You'll build the required data in my_complicated_calculation().

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.