Drupal.attachBehaviours() on Block that got rendered via ajax call i'm rendering a form and using an alter hook for changing the form to submit via ajax. This works like a charm. ( Drupal 8 webform with webform_ajax )

Now i want to render the form via ajax into the content. This also works.

Because the content is not there on page load i have to re-apply the drupal behaviours.

This is the thing i can't get to work.

Here's the code i use:
Form.js

(function ($, Drupal) {

  'use strict';

  var $modal = $('#modal');
  var url = $('.block-system-main-block &gt; article.node').attr('about');

  Drupal.behaviors.formInModal = {
    attach: function (context, settings) {
      $(context).find('.js-engagement-link').once('js-engagement-link').each(function () {
        var targetForm = $(this).data('target');

        $(this).click(function(){
          $.ajax({
            url: '/contact_bridge/webform/' + targetForm
          }).done(function(response) {
            $modal.find('.modal-content').first().html(response);
            $modal.foundation('open');
            Drupal.attachBehaviors($('#modal')[0], settings);
          });
        });
      });
    }
  };
})(jQuery, Drupal);


Form alter:

public function formAlter(array &amp;$form, FormStateInterface $formState, $formId) {
  $webformSubmission = $formState-&gt;getFormObject()-&gt;getEntity();
  if ($this-&gt;isAvailable($webformSubmission-&gt;getWebform())) {
    $ajax = $this-&gt;getAjaxProperties($formId);
    $form['#prefix'] = '&lt;div id="' . $ajax['wrapper'] . '"&gt;';
    $form['#suffix'] = '&lt;/div&gt;';
    $form['actions']['submit']['#ajax'] = [
      'callback' =&gt; '\Drupal\webform_ajax\Controller\WebformAjaxController::ajaxSubmission',
      'wrapper' =&gt; $formId . '_wrapper',
    ]
  }
}


I tried many different calls to attachBehaviours, nothing seems to work. The alter hook is applied to the form and the ajax wrapper is there.

-- edit1 --

Here the code on the backend side for rendering the block:

&lt;?php

namespace Drupal\contact_bridge\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Drupal\webform\Entity\Webform;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 *
 */
class ContactBridgeController extends ControllerBase {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManger;

  /**
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container-&gt;get('entity_type.manager'),
      $container-&gt;get('renderer'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(
    EntityTypeManagerInterface $entityTypeManager,
    RendererInterface $renderer
  ) {
    $this-&gt;entityTypeManger = $entityTypeManager;
    $this-&gt;renderer = $renderer;
  }

  /**
   * @param string $webformid
   * @return \Drupal\Core\Render\HtmlResponse
   */
  public function getWebformBlockHtml($webformid) {
    $webform = Webform::load($webformid);
    $renderArray = $this-&gt;entityTypeManager()-&gt;getViewBuilder('webform')-&gt;view($webform);

    $html = $this-&gt;renderer-&gt;renderPlain($renderArray);
    return HtmlResponse::create($html);
  }

}


And the routing:

contact_bridge.webform:
  path: 'contact_bridge/webform/{webformid}'
  defaults:
    _controller: '\Drupal\contact_bridge\Controller\ContactBridgeController::getWebformBlockHtml'
  requirements:
    _permission: 'access content'
    webformid: ^[a-zA-Z0-9_]+


Can somebody tell me what i'm doing wrong?

Thanks in advance.
Ok, there are a few things that need to be done:


Create a custom ajax command
Create the JS to handle that custom command
Return an AjaxResponse from getWebformBlockHtml(), that contains that custom command from step 1
Ajaxify the response when your ajax is complete


You can do that as follows:

Step 1 - Create a custom ajax command

namespace Drupal\[MODULENAME]\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class MODULENAMELoadFormCommand implements CommandInterface
{
  protected $form;

  public function __construct($form)
  {
    $this-&gt;form = $form;
  }

  /**
   * Implements Drupal\Core\Ajax\CommandInterface:render().
   */
  public function render()
  {
    return [
      'command' =&gt; 'MODULENAMELoadFormCommand',
      'form' =&gt; $this-&gt;form,
    ];
  }
}


Step 2 - Create the JS to handle that custom command

Add the following to your JavaScript that you're loading on page load:

Drupal.AjaxCommands.prototype.MODULENAMELoadFormCommand = function(ajax, response)
{
  $modal.find('.modal-content').first().html(response.form);
  $modal.foundation('open');
  Drupal.attachBehaviors($('#modal')[0], settings);
};


Step 3 - Return an AjaxResponse from getWebformBlockHtml() that contains that custom command from step 1

use Drupal\Core\Ajax\AjaxResponse;

public function getWebformBlockHtml($webformid) {
  $response = new Ajaxresponse();

  $webform = Webform::load($webformid);
  $renderable = $this-&gt;entityTypeManager()-&gt;getViewBuilder('webform')-&gt;view($webform);

  $rendered_form = \Drupal::service('renderer')-&gt;renderRoot($renderable);
  $response-&gt;setAttachments($renderable['#attached']);

  $response-&gt;addCommand(new MODULENAMELoadFormCommand($rendered_form));

  return $response;
}


Step 4 - Ajaxify the response when your ajax is complete

Modify your original Ajax Call to look like this:

$.ajax({
  url: '/contact_bridge/webform/' + targetForm,
  success:function(response) {
    var ajaxObject = Drupal.ajax({
      url: "",
      base: false,
      element: false,
      progress: false
    });

    // Simulate an AJAX response having arrived, and let the Ajax
    // system handle it.
    ajaxObject.success(response, "success");
  }
});