3

I couldnt find an answer to this question in Drupal 8.

I've created a simple custom module:

mymodule.info.yml

name: 'mymodule_name'
description: 'basic module for custom implementations'
package: 'custom'
type: module
version: '8.x-1.0'
core: '8.x'

mymodule.module

function mymodule_views_post_execute(\Drupal\views\ViewExecutable $view) {
    $view->setTitle('Foo');

}
function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
    $view->setTitle('Foo');
}

I tried this hook implementations separately, not at smae time. Both changes the view title, but my custom theme doesnt work.

I also tried in my custom theme the following code:

function mytheme_preprocess_views_view(&$variables) {
    $view = $variables['view'];
    $view->build_info["title"] = "Foo";
}

It prints "Foo" inside view content, it doesnt override view title.

Any idea?

1
  • 1
    Is there a particular reason why you want to do this using a module and not the through the Views UI?
    – No Sssweat
    Dec 30, 2016 at 13:51

1 Answer 1

2

You probably want to change the global title used for the title block. This is retrieved from the route. The route for a view is built from the view configuration when you save a view (or clear the cache). The title in the route is static. If you want to change it, modify it in the view configuration. You can do this in ui or in code.

If you want to make this dynamically, you can replace the static _title in the view route with a title controller _title_callback to provide a different title on every request.

4
  • What if I am using the view in a block?
    – albertski
    Aug 10, 2017 at 18:20
  • @albertski, the issue here is about the page title. Blocks don't set page titles, so this is a different topic.
    – 4uk4
    Aug 10, 2017 at 18:45
  • @4k4, thanks for the nice answer. Can you please explain more on your solution?
    – Pupil
    Jan 16, 2018 at 6:41
  • @Pupil Alter the existing route using a RouteSubscriber. The route will be call view.VIEW_MACHINENAME.PAGE_MACHINENAME.
    – Tim
    Apr 11, 2018 at 7:52

Your Answer

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

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