0

I have a view of taxonomy terms with exposed filter. Main view page: site.com/view

I have a text field with 16 different values and urls:

  • site.com/view/1
  • site.com/view/2
  • site.com/view/...
  • site.com/view/16

Depending on passed argument I change View title like this:


use \Drupal\views\ViewExecutable;
function theme_views_pre_render(ViewExecutable $view) 
{
  
  if( $view->id() == 'MY_VIEW_ID' && $view->current_display === 'VIEW_DISPLAY' && $view->args[0] != 'All')
  {
    $view->setTitle(gamesGenreTitle($view->args[0]));
  }
}

function gamesGenreTitle($val)
{
  $options = options_allowed_values(\Drupal::service('entity_field.manager')->getFieldStorageDefinitions('taxonomy_term')['field_genre']);
  return $options[$val];
}

gamesGenreTitle() is getting labels of my field in order to put them to the title.

It works, but it is not changing the head <title> tag!

I've tried theme_preprocess_html(&$variables) with this code:

  $view_id = \Drupal::routeMatch()->getParameter('view_id');

  $view = \Drupal\views\Views::getView($view_id);

But it only gets the view id and I can't access args there in order to change title on only needed pages.

My second guess, which I haven't tried yet, is to validate and explode to array current path, using \Drupal::service('path.current')->getPath();, get the last digit and pass it to gamesGenreTitle().

Or maybe there is better way?

1 Answer 1

1

Don't necessarily need to access the view object ($view) to get the arguments. You can check all arguments by doing so

$params = Drupal::routeMatch()->getParameters();

Usually you'll find that if you are accesing a view with contextual filters/parameters there will be "arg_0, arg_1" parameter keys

var_dump($params);
// object(Symfony\Component\HttpFoundation\ParameterBag)#323 (1) { ["parameters":protected]=> array(4) { ["view_id"]=> string(18) "sample_view" ["display_id"]=> string(6) "page_1" ["arg_0"]=> string(26) "251" } }

Then you can do

$params = Drupal::routeMatch()->getParameter('arg_0');
1
  • Thanks! You saved my day! )))
    – bigboy
    Jul 16, 2021 at 10:42

Your Answer

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

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