How do I keep unique form id for ajaxified form? I have a form(which is extending the FormBase class) that requires entity as argument(but I am not manipulating with this entity so that's why I am not using the EntityForm which is irrelevant to this issue but just FYI). The form uses data from the entity to build the form id. I am instantiating the form as object and I am keeping the entity as property on the form.

Due to the fact that I have multiple such forms on a single page I need the form id to be unique and matching the provided entity object to avoid collision of submitted values. In Drupal 7 this was taken care of via hook_forms().

Now I want to ajaxify this form but there is an issue that after the first submission the entity object is no longer available to the form. I have stored the data I need in the $form_state but I cannot access this in the getFormId() method.

So I have made the form id non-unique and each form instance has the same id. I have tried to get around this issue by setting the form id in the form array itself as #id attribute but that did not helped.

So my question is how to have an ajaxified form with unique form id that is based on data from provided argument to the form?



This is how I am invoking the form(in lazy loader):

$entity = $this-&gt;entityManager-&gt;getStorage($entity_type)-&gt;load($entity_id);
$form = new MyForm($entity);
return $this-&gt;formBuilder-&gt;getForm($form);


and the form itself:

class MyForm extends FormBase {

  private $entity;

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

  public function getFormId() {
    return 'my_form_' . $this-&gt;entity-&gt;getEntityTypeId() . '_' . $this-&gt;entity-&gt;id();
  }

}
So the issue was that I was calling the getFormId() in the form itself to build the html id for the ajax wrapper. For rebuilt form the entity object that I provided as argument to constructor was not available anymore so calling this method caused it to look for that entity object to extract data to build the id from and since it no longer exists it caused this issue.