Score:1

Use AJAX not working when view is rendered programmatically

in flag

I have a view that is being rendered like this

$view = Views::getView('view_id');
$view->setDisplay('block_1');
$view->execute();
$render = $view->render(); 
$html = \Drupal::service('renderer')->render($render);

The $html variable is being returned in the build method of a Block

public function build() {
    return array(
      '#theme' => 'theme_template',
      '#view' => $html,
    );
  }

Then being outputted in the twig file {{ view }}

The view is being rendered but the pagination does not use ajax instead it reloads the page with the query string ?page=1

I have found a similar question but this is for drupal 7: Use ajax not working in views block displayed programmatically

Thank you in advance!

4uk4 avatar
cn flag
You shouldn't render too early and you don't need to, templates can print render arrays. Also Views provides already a block plugin: /core/modules/views/src/Plugin/Block/ViewsBlock.php.
Stephan Sutter avatar
in flag
Hi @4k4, thanks for replying! I have tried to use the $render variable instead but still the ajax is not being used. Im going to look into ViewsBlock but do you have any links on how to use it?
No Sssweat avatar
ua flag
`do you have any links on how to use it?` @StephanSutter you just go to `/admin/structure/block` and place it like any other block. You can give it visibility restriction so it only appears on certain page(s).
Score:0
ua flag

Try like this

$view = Views::getView('view_name');
$view->setDisplay('view_machine_name');
$view->execute();

public function build() {
    return array(
        '#type' => 'view',
        '#name' => 'view_name',
        '#view' => $view,
        '#display_id' => 'block_1',
        '#embed' => TRUE,
        '#cache' => $view->getCacheTags(),
    );
}

If not use Twig Tweak and on the block's or page's template file do

{{ drupal_view('view_name', 'block_1') }}

Twig Tweak module provides a Twig extension with some useful functions and filters that can improve developer experience.

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.