0

I'm using a Geolocation field in views to order results by distance. The module provides a special views proximity plugin/field, which can be used in the "sort" section of the view. This plugin/field has a "proximity setting" (lat/long) to define the center point for distance calculation. I got this far in views UI and this all works.

I now need to programmatically change that center point based on a custom logic derived from the current user, but I don't know which views hook to use to alter this field setting.

Tried, didn't work:

function MYMODULE_views_pre_view($view, $display_id, &$args) {
  //my field's machine name is "field_geo"
  $geoField = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofield) is empty

  //suffix "_proximity" seems to be added by geolocation module, but does not work either
  $geoFieldProximity = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofieldProximity) is empty
}

I've got two questions:

  1. Is pre_view the correct hook to alter the field setting? (If not, which hook should I use instead?)
  2. How to I get/set those field settings?
    I thought I need to use $view->display_handler->getHandler() but didn't get any results.

1 Answer 1

0

Digging through the exported views.yml config helped me to get on the right track:

function MYMODULE_views_pre_view($view, $display_id, &$args) {

  if ($view->id() == 'WHATEVER' and $display_id == 'MY_DISPLAY') {
    $allFields = $view->display_handler->getOption('fields');

    $user = _MY_BUSINESS_LOGIC();
    if (!$user->get('field_geo')->isEmpty()) {
      $allFields ['field_geo_proximity']['proximity_lat'] = $user->get('field_geo')->lat;
      $allFields ['field_geo_proximity']['proximity_lng'] = $user->get('field_geo')->lng;
      $view->display_handler->overrideOption('fields', $allFields);
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.