function CacheExampleForm::createExpiringItem
Same name in other branches
- 4.0.x modules/cache_example/src/Form/CacheExampleForm.php \Drupal\cache_example\Form\CacheExampleForm::createExpiringItem()
Submit handler to create a new cache item with specified expiration.
File
-
modules/
cache_example/ src/ Form/ CacheExampleForm.php, line 235
Class
- CacheExampleForm
- Form with examples on how to use cache.
Namespace
Drupal\cache_example\FormCode
public function createExpiringItem($form, &$form_state) {
$tags = [
'cache_example:1',
];
$interval = $form_state->getValue('expiration');
if ($interval == 'never_remove') {
$expiration = CacheBackendInterface::CACHE_PERMANENT;
$expiration_friendly = $this->t('Never expires');
}
else {
$expiration = time() + $interval;
$expiration_friendly = $this->dateFormatter
->format($expiration);
}
// Set the expiration to the actual Unix timestamp of the end of the
// required interval. Also add a tag to it to be able to clear caches more
// precise.
$this->cacheBackend
->set('cache_example_expiring_item', $expiration_friendly, $expiration, $tags);
$this->messenger()
->addMessage($this->t('cache_example_expiring_item was set to expire at %time', [
'%time' => $expiration_friendly,
]));
}