5

I have two fields (consider field_A, field_B). Anyone should see only one of these 2 fields based on their IP address:

  • If users from US access the page, only field_A should be visible.
  • For other countries, field_B should be visible.

How can I achieve this?

3
  • I update my answer, take a look
    – Yuseferi
    Nov 14 '15 at 8:21
  • Both answers works for me. Don't know which is better approach. Thanks for your answers.
    – user50991
    Nov 14 '15 at 8:38
  • I include his answer in my alternative solution with implementation :)
    – Yuseferi
    Nov 14 '15 at 8:46
1

You can make use of Geo Ip to do this. Install Geo Ip by following the instruction mentioned in the link http://www.beginninglinux.com/home/php/ubuntu-php-5-geo-ip

Make use drupal ip_address() function to get user ip address.

function test() {
  $code = geoip_country_code_by_name($ip);
  if ($code == 'US') {
    //hide  field B
  }
  else {
    //hide field A
  }

}

geoip_country_code_by_name returns country code. I think this approach gives you solution.

1

If you want show and hide your field according to country that detected by user IP first you should use a module that detect user country (like ip2country module) and if it have javascript API to detect IP use it else where in hook_form_alter detect country and hide field something like

function yourmoudle_form_alter(&$form,$form_state,$form_id){
 if($form_id=='your_form_id'){
     $ip = $_SERVER['REMOTE_ADDR'];
      $country_code = ip2country_get_country($ip);
    if($country=='US'){
     hide($form['field_b']);
   }
  }
}

Alternative Solution
Also you can handle it without module and use Geo IP and as @Vamsi suggest you can

Install Geo Ip by following the instruction mentioned in the link http://www.beginninglinux.com/home/php/ubuntu-php-5-geo-ip Make use drupal ip_address() function to get user ip address.

geoip_country_code_by_name return Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

function yourmoudle_form_alter(&$form,$form_state,$form_id){
 if($form_id=='your_form_id'){
     $ip = $_SERVER['REMOTE_ADDR'];
      $country_code = geoip_country_code_by_name($ip);
    if($country=='US'){
     hide($form['field_b']);
   }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy