I am trying to find the correct views hook to alter/add a contextual filter to a views block that's being rendered in a template. (Using drupal_view and the twig tweaks module).
The view is setup to accept a contextual filter that is provided in the URL by default. It works great on that page, however it's been requested that the view also display on a sub-page of this main page, in where the URL does not contain the contextual filter. Therefore, I am trying to find a views hook that I can reliably attach the contextual filter to and have it work every page load.
I have tried using hook_views_pre_view()
, however this appears to only work once between cache clears, as if I clear cache it works, then as soon as I refresh the page it stops working again until another cache clear.
Is there a way I can do this from a hook? The way the child-page is structured, I can't easily get it from the template to pass it into drupal_view() as an argument.
The current code I am using is:
function item_types_views_pre_view(&$view, &$display_id, &$args) {
if ($view->id() == 'existing_copies') {
$parameters = \Drupal::routeMatch()->getParameters();
$imcid = \Drupal::routeMatch()->getParameter('imcid');
$entity = \Drupal::entityTypeManager()->getStorage('item_type')->load($imcid);
if ($entity->bundle() == 'book_copy') {
$main_record = $entity->field_book_main_record->getString();
}
elseif ($entity->bundle() == 'book_master_copy') {
$main_record = $entity->field_master_copy_book_mr->getString();
}
$args = [$main_record];
}
}
Which like I said, works great immediately after a cache clear, but no longer works after the page is refreshed.
$view->setArguments($args);
?