Advertising sustains the DA. Ads are hidden for members. Join today

Webform Cookbook

How to embed a Webform?

Last updated on
22 November 2023

This documentation needs review. See "Help improve this page" in the sidebar.

Maybe you need to embed a Webform programmatically in a controller or even in a preprocess function?

Embed as a Block entity

If you don't need to modify the webform before rendering it, you could also load the webform as a block, if available.
The same way, to load Webform, because Block are also Entity

    $block = \Drupal\block\Entity\Block::load('myBlockID');
    $block_content = \Drupal::entityTypeManager()
       ->getViewBuilder('block')
       ->view($block);

Embed as a render array with the new element type webform

@see \Drupal\webform\Element\Webform

$output['your_form_id'] = [
  '#type' => 'webform',
  '#webform' => 'your_form_id',
  '#default_data' => ['name' => 'Custom Name'],
  '#entity_type' => 'user', 
  '#entity_id' => 1,
];

The #entity_type and #entity_id as optional parameters used to populate the Webform's source entity.

Don't forget to add the appropriate cache tags and context while using a render array, e.g.  

'#cache' => ['contexts' => ['url.path']],

Embed with Ajax

You may need to embed a Webform in a page dynamically using Ajax. 

Especially if the Webform use ajax itself - e.g. for rendering the response on the page without a forward - you should use the Drupal Ajax Commands to load it.

Actually, if you load it with JQuery\Javascript most probably the Webform Ajax won't work.

You'll need therefore to use a custom Controller:

public function render($webform_id) {
  $response = new AjaxResponse();

  $selector = '#webform-wrapper'; //the element must be present on the page.
   
  $content = [
      '#type' => 'webform',
      '#webform' => $id,
      '#cache' => [
        'max-age' => 0,
      ],
  ];

  $response->addCommand(new HtmlCommand($selector, $content));

  return $response;
}

And use a ajax link to trigger the response: 

<a href="/controller-url/{webform_d}" class="use-ajax">Insert the Webform</a>

Help improve this page

Page status: Needs review

You can: