Score:0

Change View head title programmatically

gu flag

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?

Score:1
cn flag

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');
bigboy avatar
gu flag
Thanks! You saved my day! )))
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.