#StackBounty: #8 #forms formBuilder()->getForm() outputs everything except the <form> tag?

Bounty: 100

When displaying my form with Drupal::formBuilder()->getForm($form); I noticed the <form> tag itself is missing:

<form class="flagging-myflag-edit-form flagging-form" data-drupal-selector="flagging-myflag-edit-form-iq8dn9lwifq" action="/flag/details/edit/MYFLAG/52" method="post" id="myform-myflag-edit-form--iq8dn9lWIfQ" accept-charset="UTF-8">
Everything between the form tags is printed properly.
</form>

The form still submits even without the <form> tag, but on the actual entity edit page, there is a <form> tag, so I would like to have the same tag on my custom display.

This is the code I am using:

function MYMODULE_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($node->getType() == 'MY_CONTENT_YTPE') {
    if ($display->getComponent('my_flagging_form')) {
      $flag = Drupal::service('flag')->getFlagById('MY_FLAG');
      $flagging_entity = Drupal::service('flag')->getFlagging($flag, $node);
      $form = Drupal::service('entity.manager')
        ->getFormObject('flagging', 'edit')
        ->setEntity($flagging_entity);
      $build['my_flagging_form'] = Drupal::formBuilder()->getForm($form);
    }
  }
}

According to twig debugging, the custom form is being output through core/modules/system/templates/form.html.twig, but there’s no form tag…

This is form.html.twig:

{#
/**
 * @file
 * Default theme implementation for a 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}
<form{{ attributes }}>
  {{ children }}
</form>

EDIT: I think the <form> tag is getting removed by sanitation.

Reason: in hook_form_alter(), I tried this:

  $form['beginning']['#markup'] = "HI MOM <form id='flagging-remember-edit-form'>";
  $form['beginning']['#weight'] = -20;
  $form['end']['#markup'] = "BYE MOM</form>";
  $form['end']['#weight'] = 100;

And I see HI MOM and BYE MOM but no <form> tag.

Still, I’m confused why this is happening; the form array is returned by formBuilder(), so shouldn’t Drupal go ahead and make a form out of it?

EDIT 2: I tried to render it based on the comment of @Ales:

  $form = Drupal::service('entity.manager')
    ->getFormObject('flagging', 'edit')
    ->setEntity($flagging_entity);
  $form_to_render = Drupal::formBuilder()->getForm($form);
  $renderer = Drupal::service('renderer');
  $build['remember_form']['#markup'] = $renderer->render($form_to_render);

This gives me the same output as my original code; the form is there, but the <form> tag is not…


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.