3

I have created a form that I will embed in my page with a custom module. How can I wrap this form with a div that has a specific class?

I need to add it to the build which is made with the following code.

$build = array(
          'form' => $form,
          '#type' => 'markup',
          '#markup' => $html,
          '#attached' => array(

             'library' => array('pup_viewfiles/sortfiles_libraries'),
            ),
        );
11

There are many different ways to add markup to a form in Drupal 8. In your build array, you could add a wrapper element, and then nest the form within:

$build['wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'my-form-wrapper', 'class' => ['my-form-wrapper']],
];

$build['wrapper']['form'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

Alternately you could add a '#prefix' and a '#suffix' to your form.

$form['#prefix'] = '<div class="my-form-wrapper">';
$form['#suffix'] = '</div>';

Or you could use a template for your form and add it to your theme, using the suggestion form--form-id.html.twig and add custom markup there. (Be sure to replace underscores with hyphens in the template name.)

<div id="my-form-wrapper">
  <form{{ attributes }}>
    {{ children }}
  </form>
</dv>
3

I believe that you have described the perfect use case for the container render element.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Container.php/class/Container/8.2.x

I believe your build would be something like

$build = [
  'some_name' => [
    '#type' => 'container',
    '#attributes' => [
        'class' => 'some class',
    ],
    'form' => $form,
  ],
  'some_other_name' => [
    '#type' => 'markup',
    '#markup' => $html,
  ],
  '#attached' => array(
    'library' => array('pup_viewfiles/sortfiles_libraries'),
  ],
];

Wasn't exactly sure where you wanted the html markup (this has it outside the container).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.