1

I'm trying to load a webform block via ajax.

Right now I have:

$.ajax({
    url: '/form/contact-us',
    success: function (response) {
        console.log(response);
    },
    error: function (error) {
        console.log(error);
    }
});

How do i get the form as a block and not by the full page/node?

1

Try the following steps :

  1. Create follow this how to create contact form block
  2. Create route for example form/contact-us-block :

custom_module.routing.yml

custom_module.get_contact_form_block:
  path: '/form/contact-us-block'
  defaults:
    _controller: '\Drupal\custom_module\Controller\TutorialController::getContactFormBlock'

getContactFormBlock Action in your controller

public function getContactFormBlock() {
    //- Set your block id here
    $bid = 4;
    $block = \Drupal\block_content\Entity\BlockContent::load($bid);
    $build = \Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
      ->view($block);
    return render($build)->__toString();
  }
  1. Get the block html in your Js.

    (function ($, Drupal) {
      $(document).ready(function ($) {
        $.ajax({
          url: 'form/contact-us-block',
          success: function (response) {
            console.log(response);
          },
          error: function (error) {
            console.log(error);
          }
        });
      });
    })(jQuery, Drupal);

0

If you check /admin/structure/webform/config you will find a Site-wide webform support library inclusion option.

Site wise webform support library

You will get the dialogue-library of the webform will be loaded. You can use that or customize the code to meet your own need.

UPDATE:

Use class='use-ajax' might help you load webform in modal.

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.