Render a form

use Drupal\module\Form\YourFormClass;
// then
$form = \Drupal::formBuilder()->getForm(YourFormClass::class);

A lot of my forms use Ajax so when dynamically adding them to the page, I do not want to lose the behaviours of the form. Using renderRoot ensures no behaviours are lost.


$response = new AjaxResponse();
$form = \Drupal::formBuilder()->getForm(YourFormClass::class);
$output = array(
  '#type' => 'markup',
  '#markup' => \Drupal::service('renderer')->renderRoot($form),
  '#attached' => $form['#attached'],
);
$response->addCommand(new AppendCommand('#my-selector', $output));