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.
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.
Here is a detailed summary of how to go about this:-
https://www.sitepoint.com/building-drupal-8-module-blocks-forms/
Following the above guide, you would add the completed form to the block build function, e.g.
Some more useful docs if you are new to Drupal 8 or need to dust off your knowledge:
https://www.drupal.org/docs/8/creating-custom-modules
https://www.drupal.org/docs/8/api/block-api
https://www.drupal.org/docs/8/api/form-api
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):
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.
To build a form using block module, you can easily use Webform module where you can add a form and display as a block.
If you mean to create a form programatically in the custom block, you can achieve that by creating two files shown below:
Form file (
src/Form/DemoForm.php
):Source: Building a Drupal 8 Module: Blocks and Forms.
Block file (
src/Plugin/Block/HelloBlock.php
):Source: Create a custom block.
To add a form to the Block Configuration, see: Add a Form to the Block Configuration.