What ist the correct way to load a View via Ajax and not breaking the view ajax functionality like the pager?
I tried it this way:
In a template:
<a href="/example-module/15?token=ugi2XH02Cumb3lsbSrOutwzRYSMXmn_bRKJI3FQ-hhk" class="btn use-ajax" role="button" rel="nofollow">
{{- 'Load View' -}}
</a>
In the routing file:
example_module.example:
path: '/example-module/{node_entity}'
defaults:
_controller: '\Drupal\example_module\Controller\LoadViewController::render'
_title: 'Load View'
options:
parameters:
node_entity:
type: entity:node
requirements:
_permission: 'access content'
_csrf_token: 'TRUE'
In the Controller:
public function render(NodeInterface $node_entity, Request $request) {
$node_id = $node_entity->id();
if ($request->get(MainContentViewSubscriber::WRAPPER_FORMAT) == 'drupal_ajax') {
$views_block = views_embed_view('load_view', 'block_1', $node_id);
$response = new AjaxResponse();
$selector = '#example-id';
$replace = new ReplaceCommand($selector, \Drupal::service('renderer')->render($views_block));
$response->addCommand($replace);
return $response;
}
else {
// For entities that don't have a canonical URL (like paragraphs),
// redirect to the front page.
$front = Url::fromUri('internal:/');
$response = new RedirectResponse($front);
}
return $response;
}
This code works well. With two exceptions:
- The view is not working with ajax (e.g. Pager). But the option "use AJAX" is checked in the UI --- I also tried it with the Views::getView() method and add explicit the $view->setAjaxEnabled(TRUE) option. No success.
- The Pager of the View has the URL of the controller in it, not the URL from the current rendered page.
So if you click on the Pager of the new loaded Views, the page reloads and show you on a white screen the Ajax command, but no specific error, not in the console and not in the logs.
Is this way not working or what I'm doing wrong?
use-ajax
to the pager links as well, so that the returned ajax response is handled by the client.