Maine Mike
Maine Mike

Reputation: 61

Where to specify cache context to operate on all pages?

I would like to configure my Drupal 8 website so that any time query parameter "refcode" is used to visit my site, that value is replicated on all menu links on that page. For example, using https://www.example.com?refcode=joe would add "?refcode=joe" to all menu links on that page. Once someone enters the site using a particular refcode, then using menu links to navigate around the site would preserve that refcode and using menu links to navigate away from the site would also preserve that refcode on external menu links.

When the cache is empty, this code works:

function mymodule_link_alter( &$variables )
{
    if ( $refcode = \Drupal::request( )->query->get( 'refcode' ) )
        $variables['options']['query']['refcode'] = $refcode;
}

When the page is cached, it doesn't. I have tried adding this:

$variables['#cache']['contexts'][] = 'url.query_args:refcode';

but that does not work. I think I have to add this caching directive somewhere else, but I don't know where. Is there a place where I can instruct Drupal 8 to take "refcode" into account when retrieving any cached page?

Upvotes: 2

Views: 813

Answers (1)

Maine Mike
Maine Mike

Reputation: 61

I finally figured this out. I have to determine which block types and which node types might reference the refcode query parameter and update the cache settings for them:

function mymodule_preprocess_block( &$variables )
{
    if ( $variables['base_plugin_id'] == 'system_menu_block' )
        $variables['#cache']['contexts'][] = 'url.query_args:refcode';
}

function mymodule_preprocess_node( &$variables )
{
    if ( $variables['node']->bundle( ) == 'main' )
        $variables['#cache']['contexts'][] = 'url.query_args:refcode';
}

Upvotes: 3

Related Questions