How to create a form using block module in drupal 8?

13,246

Your question is very vague, as I don't know how much you already know about modules, forms and blocks in Drupal 8. So here is a small guide what to do, further information on how to do stuff in detail would be overkill for this answer.

1. Create a new module and enable it

Look here: Naming and placing your Drupal 8 module.

Basically you create the module folder and the module info yml file to let Drupal know about the module. Then you enable it using drush or the admin area in Drupal.

2. Create the form

Look here: Introduction to Form API.

under your_module/src/Form you create the form. More details in the link above.

3. Create the block and render the form

Look here: Create a custom block.

under your_module/src/Plugin/Block/ you create the block which will render the form.

The idea is basically (code updated with suggestion from Henrik):

$builtForm = \Drupal::formBuilder()->getForm('Drupal\your_module\Form\Your‌​Form');
$renderArray['form'] = $builtForm;

return $renderArray;

Note: You don't need to wrap the $builtForm with the $renderArray, you can return just the $builtForm and be fine. I just personally like to do it that way, because often times I need to add something else to the final render array like some markup, cache settings or a library etc.

4. Place the block

Place the block in the desired region(s). Done.

Share:
13,246
user3664791
Author by

user3664791

Updated on June 28, 2022

Comments

  • user3664791
    user3664791 almost 2 years

    I want build a form using a block module in Drupal 8. I am aware of building the forms in Drupal 7 but the same seems to be different in Drupal 8.

    Request anyone who has worked on drupal8 custom forms as block to help me.

  • user3664791
    user3664791 about 8 years
    HI Frank, Thanks for your replay .
  • user3664791
    user3664791 about 8 years
    HI Frank, Thanks for your reply. I was actually trying to implement a form within a block.I am just posting the URL which represents the same.vliegtarieven.nl ...Kindly go through and suggest me way to build the flight booking form in home page.
  • Frank Drebin
    Frank Drebin about 8 years
    I already did, just look at my answer :) I am not sure what you expect from me. I am certainly not going to dictate every single line of code, because that's not what StackOverflow is about. If you have absolutely no idea about forms and so on, just google for tutorials or something, there are plenty.
  • Henrik
    Henrik almost 8 years
    You can directly build the form with: $builtForm = \Drupal::formBuilder()->getForm('Drupal\yourmodule\Form\Your‌​Form'); – anyway, nice answer.
  • dhruveonmars
    dhruveonmars almost 6 years
    @FrankDrebin Is there a way to order the items that get returned? I'm returning a form and some markup, but the form always ends up after the markup and I'd like to get the form above the markup.