1

In D8, I have a need to dynamically set the title of a views page display.

I've tried implementing both hook_views_pre_render and hook_views_post_build and setting the value of $view->build_info['title'], but Drupal seems to be ignoring it when setting the page title.

It seems like the code in Views where the title is set is in Drupal\views\Plugin\views\display\Page::execute()

The #title property on the render array in that method IS receiving my overwritten value from one of my hooks, but it's still ignore and is using the manually specified title on the display config.

What is going on!?

  • Do you have the metatag module enabled? It is still missing Views integration (drupal.org/node/2563647) so perhaps it overrides your title with the global default? – Neograph734 Feb 28 '17 at 19:37
  • I do, but if that were the case, then specific views title I specify in the views config would not work either, but it does. – Brian Feb 28 '17 at 19:39
  • Is this view using a custom template file? – No Sssweat Feb 28 '17 at 23:34
  • 1
    What is going on!? The title is set in the route definition. See drupal.stackexchange.com/questions/224217/… – 4k4 Mar 1 '17 at 8:59
4

If someone else is looking for an answer, Here is how I achieved this. I implemented hook_views_pre_render and in this hook, I implemented a method of views class setTitle. This allowed me to set the page title. Here is the complete code.

function MYMODULE_views_pre_render(ViewExecutable $view) {
 if ($view->id() == 'ABC') {
  $view->setTitle('MY CUSTOM TITLE');
 }
}

Hope this helps.

  • Just to appreciate you that this answer worked. – Pupil Dec 27 '17 at 12:48
1

If you want to change page title too you can use this snippet

\Drupal::routeMatch()->getRouteObject()->setDefault('_title', $title);

Hope this helps.

  • This is not working for me. – usmanjutt84 Aug 2 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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