0

I am currently rendering a view manually like so:

$content = \Drupal::service('renderer')->renderPlain(views_embed_view('user_admin_people', 'page_1'));

Then I'm sending the html to the page and inserting it into a div with javascript. I needed to use renderPlain() rather than render() because when I was doing that, I was getting this error:

LogicException: Render context is empty, because render() was called outside of a renderRoot() or renderPlain() call. Use renderPlain()/renderRoot() or #lazy_builder/#pre_render instead.

Now, you're probably thinking, why don't you just use render arrays normally and let Drupal handle it? Unfortunately, I can't do that, I need to render the view's html and send it to the page, which I have already done. BUT, when I do this, clicking on 'Filter' brings me to the /admin/people page of the Drupal site (on which it will do ajax filters properly, because it rendered from a normal render array).

How could I attach the javascript to this view html so that it reloads its data via ajax instead of linking me to the view's page? I have already tried Drupal.attachBehaviors(), thinking that it would run something from ajax_view.js from views (which is a confusing & large file).

Or, where would I look in core to find out more about this, or where is some good documentation to read? Am I looking in the right place in core, looking at ajax_views.js?

0

Still early rendering should be avoided whenever possible. Did you try to return the unrendered view in an ajax command?

  $view = views_embed_view('user_admin_people', 'page_1');
  $ajax_response->addCommand(new HtmlCommand('#wrapper', $view));

If you use the unrendered build array all the things you've described in the question like reattaching drupal behaviors, js, and css are handled by the ajax implementation in drupal, on the server side when assembling the response and on the client side when processing the incoming json data.

For this to work you also need to enable the option "Use AJAX" in the view user_admin_people, otherwise the "Filter" button rebuilds the form on a new page, which then happens to be the admin page.

  • Yes, I have enabled "Use AJAX", but no, I can't use that method in my project unfortunately. I need to learn as much as possible about how it works in core. I've gathered that it puts the view information in drupalSettings including the dom_id and what-not, but I haven't had enough time to try it out. – RaisinBranCrunch Mar 27 '17 at 15:01

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.