Skip to main content

Debugging Custom Code around Drupal Views

Date
2024-02-26
Client
Harvard Graduate School of Education

I like to write a lot of custom code, and most of the time it serves a purpose. This past week found a bug where this backfired a little bit.

For a recent project, we are using Selective Better Exposed Filters module to help reduce the amount of options on a filters for a view. We also have a bit of custom code for Authors to set a predefined value for one of the fields, and this is where we were adding in a bit of custom code to create that pre-selected option. Yes, it could have been done with a view reference and a contextual reference, but that is so clunky in the admin experience. If I had done it this way, the bug would not have existed.

What happens is, the module creates a new view for every filter it is filtering. If you do any custom code changes to the main view, you also have to do it to the views that selective_better_exposed_filters spawns. The module recreates the view instead of cloning the primary view. I'm not sure if this is better in some way or not. In the process of recreating the view, it does not know about your custom code.

So to fix the bug, the only good way seemed to be setting a global variable. Which isn't optimal, but no more bug.

function harvardgse_preprocess_node(&$variables) {
  ...
  // Custom view shenanigans to set filters.
  ...
  $args = &drupal_static('PPE_custom_presets', []);
  $args["port"][$tid] = $tid;
  ...
}

Then in s module file:

/**
 * Implement hook_views_pre_build().
 */
function hgse_utility_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Target PPE Finder.
  // On the assumption selective_better_exposed_filters module always sets its views Items per page to 0.
  if ($view->id() == "ppe_program_finder" && $display_id == "finder" && $view->getItemsPerPage() == 0) {
    // Check static variables presets.
    $presets = drupal_static('PPE_custom_presets');
    if ($presets) {
      $input = $view->getExposedInput();
      $input += $presets;
      $view->setExposedInput($input);
    }
  }
}

So far its working.

Related Tech