Load a ajax form with $.ajax call

Hi,

Indications
– I am using Drupal 8.2.2

The Idea:
I am trying to load a custom entity edit form that will use #ajax submit callback with jQuery ajax function.

The problem:
When I load the edit form of my custom entity and with a hook_form I add the ajax index to my form ($form[‘submit’][‘#ajax’]…) everything works fine. The ajax form behaviours work as expected and all form values changes are saved. But When I load the form of a $.ajax calls the ajax form does not work.

Maybe:
Maybe I am missing some Javascripts dependencies when I load a ajax form with $.ajax?

When I load the ajax Form with jQuery ($.ajax):

  • The form[‘#action’] is : “/form_action_cc611e1d”
  • The submit button is reloading the whole page
  • The form values are not saving

Here is some of my code:

  // code I use to load the custom entity edit form
  // content_entity_intervention = my custom entity name

   $entity = Drupal::entityTypeManager()
      ->getStorage('content_entity_intervention')
      ->load(3);

   $form_object = Drupal::entityTypeManager()
      ->getFormObject('content_entity_intervention', 'edit')
      ->setEntity($entity);

   $form = Drupal::formBuilder()->getForm($form_object);
   $form_html = Drupal::service('renderer')->render($form);

The Ajax call to load the form:

// get custom entity form with ajax
var data = {
    loadForm: true
};

$.ajax({
    url: Drupal.url('admin/ajax-records'),
    type:"POST",
    data: JSON.stringify(data),
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    success: function(response) {
        $('#form-wrapper').html(response);
        Drupal.attachBehaviors();
       $('#form-id').ajaxForm();
    }
});

The ajax call return the custom entity edit form with all the entity values, but the ajax submit button is not working and the hook_form is adding the $form[‘submit’][‘#ajax’] property.

Thank you very much.

Drupal version: 


Source: https://www.drupal.org/taxonomy/term/4/feed