To create custom forms on Drupal 8, follow the steps listed below:
1. Create a new module:
Create a module directory in the Drupal installation’s /modules folder. Inside, create a .info.yml file and a .module file.
1. Define a route:
Define a route for the form in the module’s .routing.yml file. The route defines the URL path where the form will be displayed.
1. Create a form class:
Create a form class in the module’s src/Form directory that extends the Drupal\Core\Form\FormBase class. Define the form elements within the buildForm method of the class.
1. Add a template:
Add a twig template to the module’s templates directory to define the HTML markup of the form.
1. Submit and Validate:
Define the submitForm and validateForm methods within the form class to handle form submission and validation.
1. Enable the module:
Enable the custom module by logging in as an administrator and navigating to the Extend page. Find the module and check the box next to it, then click Save.
1. Test the form:
Visit the URL defined in the routing file to test the form. The form should be displayed with the HTML markup defined in the twig template. Submit the form to test the submit and validation functions.