TYPO3: clear cache by tag for custom content element when record in backend is changed

Viewed 181

I have a sysfolder with records which get displayed in the frontend via a custom content element.

Now I have the problem that the frontend is not updated when a new record is added or an existing record is changed.

To clear the cache I'm using a hook in ext_localconf.php:

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']['foobar'] =
        \Vendor\Name\Hooks\DataHandler::class . '->clearCachePostProc';

The hook looks like this:

<?php

namespace Vendor\Name\Hooks;

use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;

class DataHandler implements SingletonInterface
{
    public function clearCachePostProc(array $params): void
    {
        if (isset($params['table']) && $params['table'] === 'tx_foo_domain_model_bar') {
            $cacheManager = GeneralUtility::makeInstance(CacheManager::class);
            $cacheManager->flushCachesByTag('1642782027');
        }
    }
}

And the content element is implemented with FLUIDTEMPLATE and a dataprocessor:

tt_content {
  foo_bar =< lib.contentElement
    foo_bar {
        templateName = myTemplate
        stdWrap.cache {
            key = tx_foo_domain_model_bar
            tags = 1642782027
            lifetime = default
        }
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
            10 {
                table = tx_foo_domain_model_bar
                pidInList = {$foo.storage_pid}
                as = foobar
            }
        }
    }
}

Everything seems to work but when I hit Cmd+R/Ctrl+R and reload the page or visit it again via the navigation, the page is not updated with the latest content.

2 Answers

I implemented the following solution.

Within the Typoscript Setup add a addPageCacheTag to your custom content element:

tt_content {
    foo_bar =< lib.contentElement
    foo_bar {
        templateName = FooBar
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
            10 {
                table = tx_foo_domain_model_bar
                pidInList = {$foo.storage_pid}
                as = foobar
            }
        }

        stdWrap.addPageCacheTags = foo_bar
    }
}

Add the clearCacheCmd to the Page TSConfig from the storage page like:

TCEMAIN.clearCacheCmd = cacheTag:foo_bar

For testing, add this to your Fluid-Template and be sure to test with a separate browser (without BE login):

<div style="color: red;"><f:format.date format="d.m.Y - H:i:s">now</f:format.date></div>

Kudos to https://daniel-siepmann.de/posts/2019/typo3-content-caching.html

Related