0

In my Drupal application, I have set some cookies through a javascript onClick method.

However, am not able to access the data until I clear the cache(admin/config/development/performance/clear caches) manually.

Is there any way to clear cache in the preprocess function of the theme.

This is how I have set cookies,

$('.icons .fa-heart-o').on('click', function(){
    z.push($(this).data("nid"));
    setCookie("fav_nids", z, 5);
});

function setCookie(cname, cvalue, exdays) {
  console.log(z);
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + z + ";" + expires + ";path=/";
}

and retrieving them in my preprocess function,

function themename_preprocess_node__wishlist(&$variables){

    /*$cache_tags = $variables['entity']->getCacheTags();
    \Drupal\Core\Cache\Cache::invalidateTags($cache_tags);*/

    drupal_flush_all_caches();  //To clear all cache or

    $renderCache = \Drupal::service('cache.render');
    $renderCache->invalidateAll(); 

    $variables['#cache']['contexts'][] = 'url.path';

    $cookie_name = 'fav_nids';

    if(!isset($_COOKIE[$cookie_name])) {

      $wishlist_count = 0;
      $variables['wishlist_empty'] = "No items in the wishlist";

    } else {

        $cookie_value = $_COOKIE[$cookie_name];
        $wishlist_data = explode(" ",$cookie_value);
        $wishlist_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($wishlist_data);

        foreach ($wishlist_nodes as $node){
            $variables['wishlist_nodes_data'][] = $node;
        }

      //echo "<pre>"; var_dump($variables['wishlist_nodes_data']); exit;
    }

}

I tried a few ways to clear cache in preprocess function, but nothing works only manually clearing cache working, and that is not ideal at all.

Any help appreciated. TIA.

2

0

Browse other questions tagged or ask your own question.