1

I am loading database values in my FORM and seems form is CACHING and loading old data from the database.

I have followed instruction here (How do I prevent a form from being cached for Anonymous users in D8?) but still old data is loaded in form fields.

Here is my code and would appreciate if anyone can shed light where I am missing;

....

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {

// Define form fields.
$form['#cache']['max-age'] = 0;

$form['name'] = array(
  '#type' => 'textfield',
  '#size' => 80,
  '#title' => t('Your Name'),
  '#default_value' => $result->name,
);

return $form;
}

....

Do I have to add 'use Drupal\Core\Cache;' on top of this file?

Thanks a lot.

2

In the linked question the module Internal Page Cache was not enabled. If you don't want to disable page caching for all pages, but only for this form page, then add \Drupal::service('page_cache_kill_switch')->trigger() before you return the form:

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {

// Define form fields.
$form['#cache']['max-age'] = 0;

$form['name'] = array(
  '#type' => 'textfield',
  '#size' => 80,
  '#title' => t('Your Name'),
  '#default_value' => $result->name,
);

\Drupal::service('page_cache_kill_switch')->trigger();

return $form;
}

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.