How to create a custom form and submit data in to database in Drupal 8 and 9

In this article we are discussing about steps required to create a custom form. Here we are creating a custom form in our custom module with validations and submit data in to a custom table.

So after applying below changes you can a see a custom form as below which will save data in to the  table students.

Assume  dn_students is our custom module. Follow below 3  steps of implementation in this custom module.

Step1 –  Create table schema in *.install file

Create a dn_students.install file in your module root folder path and place below code.

During installation of dn_students module, students table will be created in your database with fields fname, lname , id, age and marks.

Step 2  – Create page path and form mapping in *.routing.yml

Add below code in dn_students.routing.yml

So, our form page URL is http://yourdomain/students/add

Next, we have to create form php file.

Step 3 –  Create a form php file in path  /src/Form 

Create StudentForm.php file in module path /src/Form

This file has three functions ,

  • BuildForm function for bulding form elements
  • ValidateForm function for validating form values
  • submitForm function for handing form data insertion to database.

See below full code in StudentForm.php.

Now install the file and access url   /students/add.

You can see submitted details in students table as below.

 

Download sample module code here.

 

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...