DEV Community

Rahul Khan
Rahul Khan

Posted on

Custom Module & DB Table in Drupal 9

We will be creating a custom module in Drupal 9 to build a custom form & store the data in a custom table in the database.

Step 1: Name of the Module
We need to create a custom module under 'modules/custom' folder. We will name the folder as 'userinfo'

Step 2: Creating the info.yml file
We have to create a yaml file with the machine name of our module for Drupal to be able recognize the module. We will name the file as 'userinfo.info.yml'

name: User Info
type: module
description: A custom module to enter user information
package: Custom
version: 1.0
core_version_requirement: ^8 || ^9
Enter fullscreen mode Exit fullscreen mode

Step 3: Creating the routing.yml file
Next step is to add a userinfo.routing.yml file under the 'userinfo' directory.
Under path, we specify the URL path for adding user information.

userinfo.form:
 path: '/add-user-info'
 defaults:
  _title: 'Add User Info'
  _form: '\Drupal\userinfo\Form\UserinfoForm'
 requirements:
  _permission: 'access content'
Enter fullscreen mode Exit fullscreen mode

Step 4: Adding the form
We will create a form named 'UserinfoForm.php' under 'modules/custom/userinfo/src/Form'. In this file, we will create a custom form to validate & submit user information.

<?php

/**
 * @file
 * Contains \Drupal\userinfo\Form\UserinfoForm.
*/

namespace Drupal\userinfo\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Url;
use Drupal\Core\Routing;

class UserinfoForm extends FormBase {
    /**
    * {@inheritdoc}
    */
    public function getFormId() {
        return 'userinfo_form';
    }

    /**
    * {@inheritdoc}
    */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form['form_info'] = array(
            '#markup' => '<h4>Saving User Info in a custom table in the database</h4><br>',
        );
        $form['first_name'] = array(
            '#type' => 'textfield',
            '#title' => t('First Name'),
            '#required' => TRUE,
            '#maxlength' => 50,
            '#default_value' => '',
        );
        $form['last_name'] = array(
            '#type' => 'textfield',
            '#title' => t('Last Name'),
            '#required' => TRUE,
            '#maxlength' => 50,
            '#default_value' => '',
        );
        $form['user_email'] = array(
            '#type' => 'textfield',
            '#title' => t('Email-ID'),
            '#required' => TRUE,
            '#maxlength' => 50,
            '#default_value' => '',
        );
        $form['user_age'] = [
            '#type' => 'textfield',
            '#title' => t('Age'),
            '#required' => TRUE,
            '#maxlength' => 20,
            '#default_value' => '',
        ];
        $form['user_city'] = array(
            '#type' => 'textfield',
            '#title' => t('City'),
            '#required' => TRUE,
            '#maxlength' => 50,
            '#default_value' => '',
        );

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save Info'),
            '#button_type' => 'primary',
        );
        return $form;
    }

    /**
    * {@inheritdoc}
    */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        if ($form_state->getValue('first_name') == '') {
            $form_state->setErrorByName('first_name', $this->t('Please Enter First Name'));
        }
        if ($form_state->getValue('last_name') == '') {
            $form_state->setErrorByName('last_name', $this->t('Please Enter Last Name'));
        }
        if ($form_state->getValue('user_email') == '') {
            $form_state->setErrorByName('user_email', $this->t('Please Enter Email-ID'));
        }
        if ($form_state->getValue('user_age') == '') {
            $form_state->setErrorByName('user_age', $this->t('Please Enter Age'));
        }
        if ($form_state->getValue('user_city') == '') {
            $form_state->setErrorByName('user_city', $this->t('Please Enter City'));
        }
    }

    /**
    * {@inheritdoc}
    */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        try{
            $conn = Database::getConnection();
            $field = $form_state->getValues();

            $fields["first_name"] = $field['first_name'];
            $fields["last_name"] = $field['last_name'];
            $fields["user_email"] = $field['user_email'];
            $fields["user_age"] = $field['user_age'];
            $fields["user_city"] = $field['user_city'];

            $conn->insert('user_info')
            ->fields($fields)->execute();
            \Drupal::messenger()->addMessage(t("User info has been succesfully saved"));
        }
        catch(Exception $ex){
            \Drupal::logger('userinfo')->error($ex->getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Creating table schema
Now, we will create a database table schema in 'userinfo.install' file to store the user information. We will place this file in the module root folder.
The table name is 'user_info' with the following fields: user_id, first_name, last_name, user_email, user_age & user_city.

<?php
use Drupal\Core\Database\Database;

/**
 * Implements hook_schema().
 */
function userinfo_schema(){
    $schema['user_info'] = array(
        'description' => 'The table for storing the user information',
        'fields' => array(
            'user_id' => array(
                'description' => 'Primary identifier for User',
                'type' => 'serial',
                'not null' => TRUE,
                'unsigned' => TRUE,
            ),
            'first_name' => array(
                'description' => 'User First Name',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
           'last_name' => array(
                'description' => 'User Last Name.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
            'user_email' => array(
                'description' => 'User Email ID',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'user_age' => array(
                'description' => 'Age of User',
                'type' => 'int',
                'length' => 100,
                'not null' => TRUE,
            ),
            'user_city' => array(
                'description' => 'User City',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
            ),
        ),
        'primary key' => array('user_id'),
    );
    return $schema;
}
Enter fullscreen mode Exit fullscreen mode

Once everything is done, we can enable the module & hit the URL mentioned in the routing file.

Top comments (2)

Collapse
 
kopeboy profile image
Lorenzo Giovenali

So this will add all the info as multiple columns of the same table? How do you map the user_id?!

Collapse
 
rahulk1011 profile image
Rahul Khan

Yes, this will add all the info in multiple columns of same table with auto-increment of user_id in the table. The user_id will be assigned automatically.
Also, the table is a custom table, not like user_field_data table of Drupal