- 3382 views
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
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'
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;
}
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');
}
}
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 );
}
}
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
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.