Tutorial

How to create custom form in Drupal 8 and insert record into mysql database

In this tutorial I will show you how to create custom form in Drupal 8 , After that will insert the form data into our MYSQL database .

I will create new module under /modules/custom/hello_world , hello_world is my module name . Pleease find the below folder structure .

Pridal/a lubo dňa Ut, 01/19/2021 - 08:43
Create the YML file in module folder

How drupal will know that we have created the custom modlue with .info.yml, Drupal comes to know that we have created the custom module . I will name the file as hello_world.info.yml
below goes the code

name: Hello world
description: A Custom module to store detail information about employee.
core: 8.x
package: Custom
type: module

 

Create routing.yml file

I will create the link form which I will redirect to my custom url, with routing.yml drupal comes to know that there is url for the module. I will name the file as hello_world.routing.yml

* path: '/hello/details' form here we can view our custom form fields .
* path: '/hello/details/thankyou' After the form get successfull submited user will get the thankyou page with message .
* path: '/hello/getdetails' What all record get inserted into data base we can get in json format data .

Below goes the code:

hello.form:
 path: '/hello/details'
 defaults:
   _title: 'Application form'
   _form: '\Drupal\hello_world\Form\HelloForm'
 requirements:
   _permission: 'access content'
 
hello.thankyou:
 path: '/hello/details/thankyou'
 defaults:
   _title: 'Thank You Page'
   _controller: '\Drupal\hello_world\Controller\ThankyouController::successpage'
 requirements:
   _permission: 'access content'
 
hello.getdetails:
 path: '/hello/getdetails'
 defaults:
   _title: 'Fetch detail of Employee'
   _controller: '\Drupal\hello_world\Controller\ThankyouController::getDetails'
 requirements:
   _permission: 'access content'

 

Create .install file

Now we have to create table structure in our code we need .install this will create table for us in your drupal database when we install the module. I will name the file as hello_world.install

Below goes the code:

<?php
function hello_world_schema() {
  $schema['employee'] = array(
    'description' => 'Stores value in custom table',
    'fields' => array(
      'pid' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique id for employee',
      ),
      'first_name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name First name of a person.',
      ),
      'last_name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Store last name of a person',
      ),
       'email' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Store email of a person',
      ),
      'role' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Store role of a person',
      ),
      'pincode' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The pincode of his area',
      ),
    ),
    'primary key' => array('pid'),
  );
 
  return $schema;
}

 

Create the custom form via Form API

Now will create our custom form in HelloForm.php file we will extend drupal core FormBase, FormStateInterface class to create the form with following fields in it First Name, Last Name, Email etc. On form submit data will get inserted into employee table. I will name the file as HelloForm.php

Below goes the code:

<?php
/**
 * @file
 * Contains \Drupal\hello_world\Form\HelloForm.
 */
namespace Drupal\hello_world\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Database\Database;
 
class HelloForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'hello_form';
  }
 
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['first_name'] = array(
      '#type' => 'textfield',
      '#title' => t('First Name:'),
      '#pattern' => '[A-Za-z]+',
      '#required' => TRUE,
    );
    $form['last_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name:'),
      '#pattern' => '[A-Za-z]+',
      '#required' => TRUE,
    );
    $form['email_address'] = array(
      '#type' => 'email',
      '#title' => $this->t('Email:'),
      '#pattern' => '[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$',
      '#required' => TRUE,
    );
 
    $form['pincode'] = array(
      '#type' => 'textfield',
      '#title' => t('Pincode:'),
      '#size' => 6,
      '#pattern' => '[0-9]{6}',
      '#required' => TRUE,
    );
 
    $form['employee_role'] = array (
      '#type' => 'select',
      '#title' => ('Employee Role'),
      '#options' => array(
        'manager' => t('Manager'),
        'executive_manager' => t('Executive  Manager'),
        'fresher' => t('Fresher'),
        'ceo' => t('CEO'),
        'team_lead' => t('Team Lead')
      ),
    );
 
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );
    return $form;
  }
 
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $conn = Database::getConnection();
    $conn->insert('employee')->fields(
      array(
        'first_name' => $form_state->getValue('first_name'),
        'last_name' => $form_state->getValue('last_name'),
        'email' => $form_state->getValue('email_address'),
        'pincode' => $form_state->getValue('pincode'),
        'role' => $form_state->getValue('employee_role'),
      )
    )->execute();
    $url = Url::fromRoute('hello.thankyou');
    $form_state->setRedirectUrl($url);
   }
 
  public function validateForm(array &$form, FormStateInterface $form_state) {
    //$email = $form_state->getValue('email_address');
 
  }
}

 

Create the Controller file

Now I will create a controller ThankyouController.php, when the user submit the form he can get success page message method I used successpage(). User can view all the form data added in JSON format with getDetails() method. I will name the file as ThankyouController.php

Below goes the code

<?php
namespace Drupal\hello_world\Controller;
 
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Database\Database;
 
/**
 * Provides route responses for the Example module.
 */
class ThankyouController extends ControllerBase {
 
  /**
   * Returns a simple page.
   *
   * @return array
   *   A simple renderable array.
   */
  public function successpage() {
  //display thankyou page
    $element = array(
      '#markup' => 'Form data submitted',
    );
    return $element;
  }
 
  public function getDetails() {
  //fetch data from employee table.
  $db = \Drupal::database(); 
  $query = $db->select('employee', 'n'); 
  $query->fields('n'); 
  $response = $query->execute()->fetchAll();
    return new JsonResponse( $response );
  }
}

 

Installing the module

Finally time to install our custom module and submit form data into database.

With following url you can see the form:

http://localhost/site_local/hello/details
Done!

To see which all records got inserted I have shown all the record in JSON format : http://localhost/site_local/getdetails

Disclaimer:

Editor's note: This article was re-written and "stolen" from website http://cmstoddler.com/how-create-custom-form-drupal-8-and-insert-record-mysql-database which unfortunately no longer exists. I find the article very helpful in my module development in custom project, and very clear written. It was NOT written by me, but the following author, which all the credit goes to:

Mr. Surendra Chauhan , A Lead developer experties in Drupal , Wordpress , PHP Frameworks , Server Managment.

Might interest you

Module
In Drupal Commerce, there is no way how to add new payment methods via user interface, you just need to write a module. So I did. All it…
Tutorial
If you are a newbie like I am and struggling with setting the proper MYSQL my.cnf config, use this simple program to prevent swapping.…

Recommended

Article
32 views
For the past few days I am trying to comprehend why / how this blockchain even gained it'…
Tutorial
95 views
This sketch is quite easy, I used Arduino Nano with OLED 0.96″ display 128×64 resolution…
Tutorial
157 views
While working on a fairly complex website with very complex views setup, including tens…
Tutorial
14 views
In this case we have two options, either we use hook_user_presave() or we can create new…
Tutorial
15 views
When using Swiftmailer under Drupal 8 / 9 it automatically sets the headers for sender to…
Tutorial
7 views
Yes, IOS / Safari is the new internet explorer. Amount of time I spend on debugging…
Tutorial
43 views
There is a very handy function in Drupal 8 / 9, allowing developers refresh view when…
Tutorial
22 views
Often, when doing SEO checkups, SEO specialist come up with adding Schema.org…
Tutorial
174 views
I needed to test my contracts against USDC contract, specifically I needed ERC-721 mint…
Tutorial
85 views
If you are a newbie like I am and struggling with setting the proper MYSQL my.cnf config…
Tutorial
25 views
I had trouble to set this up properly, because documentation is quite misleading or often…
Article
72 views
As the title says, DO NOT in any circumstances install ANY bitcoin price extension to ANY…
Tutorial
278 views
This is (or should be) a working example of sending some Ether between two addresses.…
Module
45 views
This list was fetched from Zapper, with their /v1/token-list endpoint. Which you can…
Tutorial
143 views
In the last months I am being pretty much bombarded by my clients with asking what…