4

What exactly is the best way to accomplish this? I can pass the $form object returned from getForm to drupal_render() and get the correct themed output fragment but the API docs say this function will be deprecated in D9 and to use the renderer service instead.

When I use:

\Drupal::service('renderer')->render($form)

I get

You have requested a non-existent service "renderer". Did you mean one of these: "render_html_renderer", "html_fragment_renderer", "html_page_renderer"?

When I use:

\Drupal::service('render_html_renderer')->render($form)

I get a valid object with a protected content() method, which contains the string, but I can't seem to find any valid public functions to access this.

I can normally use the route builder to point to a form controller that I've created but, in this instance, I just want to pull an existing form, get the HTML content, and display it - hopefully as a variable in a preprocess function. I don't necessarily want to create a block, since I probably won't be reusing it.

What is the best way to do this? Keep using drupal_render() until D9? Can somebody point me in the right direction?

1
  • Aha! Devel is appearently quite useful these days as I spotted a available methods tab within and found the getContent() method. Commented Nov 25, 2014 at 15:45

3 Answers 3

6

There are almost no reasons to manually call drupal_render(), you can use/return render arrays almost anywhere, controllers, blocks and also in twig templates.

If you do $variables['form'] = $your_form;in preprocess, then {{ form }} in your template should just work.

0

I think should work if you do something like

$form = \Drupal::service('render_html_renderer')->render($form);
print $form->__toString();
-1

Try using renderRoot() instead of render(), e.g.

\Drupal::service('renderer')->renderRoot($form)

Renders final HTML given a structured array tree.

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.