Drupal - Display webform in a modal
Displaying a weform in modal (might be called popup as well) it is a lot simpler than you thought
Lets assume your webform has URL /contact
than you can create a link in the following manner
<a class="use-ajax" data-dialog-type="modal" href="/contact>Contact US</a>
Pressing that link will have your form open in a modal with error validation and messages inside the modal
NOTE:
At least in my case I had to also add the following hook_preprocess_page
in the .theme
file
function THEMENAME_preprocess_page(&$vars) {
//custom logic of when to include the library
// ....
$vars['#attached']['library'][] = 'core/drupal.dialog.ajax';
}
Some people have reported that this is not needed but I assume some other module included this library for them ...
The only solution to load the webform with formBuilder that finally worked for me is based on the following documentation of how to embed a webform. Here's my code:
/**
* Callback for opening the modal form to create an article.
*
* @return Drupal\Core\Ajax\AjaxResponse
* A responseObject for Ajax.
*/
public function addArticle() {
// Get the currently logged in user account.
$user = $this->currentUser();
if ($user->hasPermission('create article content')) {
$response = new AjaxResponse();
// Load the webform as indicated here:
// https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform
$output['add_form'] = [
'#type' => 'webform',
'#webform' => 'add_news_webform',
];
// Add a modal dialog command to the $response object.
$response->addCommand(new OpenModalDialogCommand(t('Create Article'), $output, ['width' => '500']));
return $response;
}
}
Drupal 8 Webform can be opened in modal dialogs using links with the .webform-dialog class
a. Common settings Configuration » Forms: /admin/structure/webform/config
1. FORM DIALOG SETTINGS - Dialog options: set option Enable site-wide dialog support. Do patch for load script by preg_match
2. Check Form URL path settings
b. On webform settings Settings » General (example: contact) /admin/structure/webform/manage/contact/settings
1. Enable options URL PATH SETTINGS: Allow users to post submissions from a dedicated URL
2. Copy link from DIALOG SETTINGS