ADVERTISEMENTS

Build your custom module in drupal 8

Nitasha BatraOct 04, 2020
Build your custom module in drupal 8

Custom modules or plugins always meet our requirements in any CMS or Framework. Drupal is already having thousands of core and contributed modules on community but sometimes we get some specific requirement for your project which is not available on community.

So, we can move forward to build custom module which is quite easy which will work with other existing modules. In drupal, we have flexibility to extend new feature in existing functionality or module which we can accomplish by our custom module Here we are explaining some steps to develop custom module with form and a page.

ADVERTISEMENTS

Step 01 : Create Directory

Initially, we need to create a directory in modules folder of drupal root at path [Drupal_Root]/modules/custom. We have created it with name "etutorialz".

custom module drupal 8

This name would be a machine name. So, this will have all small letter without any space.

Step 02 : Initialize Module

In this step, we have to initialize module which will connect with drupal core for working as part of drupal 8. We need to create info file i.e. etutorialz.info.yml at path [Drupal_Root]/modules/custom/etutorialz/etutorialz.info.yml. File name should be same as module machine name.

name: Etutorialz - Custom Module
type: module
description: 'This is our first custom drupal 8 module.'
package: Custom
version: 1.0
core: 8.x

 

In this file, we have defined name, type, description, package, version of module and core of module which will explain that with which version of drupal core this module will interact.

Step 03 : Setup of routes

Now, our next step is setup of routes. For this we need to create a file i.e. etutorialz.routing.yml which will contains information about routes in YAML format.

etutorialz.content:
  path: '/etutorialz/page'
  defaults:
    _controller: '\Drupal\etutorialz\Controller\DemoController::content'
    _title: 'Welcome to My Page in Drupal 8'
  requirements: 
    _permission: 'access content'

etutorialz.form:
  path: '/etutorialz/form'
  defaults:
    _form: '\Drupal\etutorialz\Form\DemoForm'
    _title: 'Welcome to My Form in Drupal 8'
  requirements: 
    _permission: 'access content'

In this routing file, we have defined these :

  • Unique key of each routing i.e. etutorialz.content
  • Path of routing i.e. /etutorialz/page. Page will be accessible by this path http://example.com/etutorialz/page
  • Controller or Form of this path i.e. DemoController & DemoForm
  • Permission of this routing. 'access content' defines that this page is accessible for anonymous user
ADVERTISEMENTS

Step 04 : Create Controller

As we defined in previous step, here we'll create file at path [Drupal_Root]/modules/custom/etutorialz/src/Controller with name DemoController.php with following content :

namespace Drupal\etutorialz\Controller;
class DemoController {
  public function content() {
    return array(
      '#markup' => 'Welcome to our Website.'
    );
  }
}

This code, we have defined content method in DemoController which is returing markup type text. We can also return a template which will camm theme file in our custom module.

Step 05 : Create Form

Similarlly above step, we'll create a file for our form at path [Drupal_Root]/modules/custom/etutorialz/src/Form with name DemoForm.php with following three methods (getFormId, buildForm, validateForm & submitForm ) which are compulsary in form.

/**
 * @file
 * Contains \Drupal\etutorialz\Form\DemoForm.
 */
namespace Drupal\etutorialz\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class DemoForm extends FormBase {
	// Define Form_Id
	public function getFormId() {
		return 'demo_etutorialz_form';
	}
	// Build / Create form
	public function buildForm(array $form, FormStateInterface $form_state) {
		$form['full_name'] = array(
		  '#type' => 'textfield',
		  '#title' => t('Full Name:'),
		  '#required' => TRUE,
		);
		$form['candidate_mail'] = array(
		  '#type' => 'email',
		  '#title' => t('Email ID:'),
		  '#required' => TRUE,
		);
		return $form;
	}
	// Validate Form
    public function validateForm(array &$form, FormStateInterface $form_state) {
      if (strlen($form_state->getValue('full_name')) < 10) {
        $form_state->setErrorByName('full_name', $this->t('Full name length is too short.'));
      }
    }
	// Submit Form
	public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
	  // Add your code to save these values. 
      drupal_set_message($key . ': ' . $value);
    }
   }
}

In above code, we have defined four methods :

  • getFormId: In this method we have defined form id.
  • buildForm: In this method we have build form fields i.e. Full Name & Email Address.
  • validateForm: In this method we are validating full name value's length should be more than 10 characters.
  • submitForm: In this method we are saving values of our submitted form .
ADVERTISEMENTS

Step 06 : Ready to Install

Now, we are ready to install our module i.e. etutorialz. You just need to login your drupal site and install module from extend admin page from top navigation bar. Once, module'll get installed properly, you can test paths i.e. /etutorialz/page & /etutorialz/form.

If you are getting ‘Page Not Found’ error, clear cache by navigating to admin > configuration > performance and test it again.

Now, you are ready with your custom module.

ADVERTISEMENTS