Score:2

How can you cache a form render array?

cn flag

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.

Kevin avatar
in flag
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.
Hershel avatar
cn flag
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.
Kevin avatar
in flag
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.
Score:2
de flag

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();
  \Drupal::cache()
    ->set($cid, $data);
}

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

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

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.