I have created a view with exposed dropdown where the default exposed value will be changed based on current country. I have got an api which will get the current country based on ip address & it's working absolutely perfect.
I am using a VPN to change the current ip address, & based on ip address the default exposed value is being changed but the problem is that, the same is working only after clear cache.
I tried to disable cache for that partiulat node using the below code, still it's not working.
function MYMODULE_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
if($node->id()==144) {
$build['#cache']['max-age'] = 0;
\Drupal::service('page_cache_kill_switch')->trigger();
}
The full code looks like this:
function MYMODULE_views_pre_build(ViewExecutable $view) {
if(($view->id() === 'myview_id') && ($view->current_display === 'block_1')) {
$exposed_input = $view->getExposedInput();
$currentIP = $_SERVER['REMOTE_ADDR'];
$ipdat = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $currentIP));
$currentCountry = $ipdat->geoplugin_countryName;
if($currentCountry=='India') {
$defaultCountryCode = 26;
$exposed_input['field_myfield_target_id'] = $defaultCountryCode;
$view->setExposedInput($exposed_input);
}
elseif($currentCountry=='Russia') {
$defaultCountryCode = 174;
$exposed_input['field_myfield_target_id'] = $defaultCountryCode;
$view->setExposedInput($exposed_input);
}
else {
$defaultCountryCode = 26;
$exposed_input['field_product_geography_area_target_id'] = $defaultCountryCode;
$view->setExposedInput($exposed_input);
}
}
}
How my application will catch the current IP address without clear cache? Thanks in advance.
Views also have caches. Please check your view's cache configs.
If you wanna dive deep and optimize more;
You can check https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts and you can use ip cache context.
If you wanna dive deep and optimize more;
You can create a country cache context plugin and cache per country instead of ip. Here is the exact example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/src/Cache/Context/CountryCacheContext.php
Additional IMPORTANT Note: Using third-party API in a Cache context plugin is a really bad idea and not sustainable. I suggest you use https://www.php.net/geoip or at least cache your API results additionally.
Regards,