How To Create Custom Module & CSS In Libraries In Drupal 9?

How To Create Custom Module & CSS In Libraries In Drupal 9?

Create Custom Module & CSS In Libraries In Drupal 9

Since there are thousands of Drupal core and contributed modules from which to pick, one would reasonably question why anyone would still want to build custom modules. The majority of the time, it is because website builders are searching for customized features to attain particular functionality or to differentiate themselves from the other businesses in their industry. When it comes to components that aren’t very common, a contributed or core module might not necessarily match all of the requirements exactly. When this happens, the development of bespoke modules comes into play.

Because Drupal is so flexible, it now allows you to build highly effective bespoke modules, which can add functionality and logic to the platform to match the specific needs of your business. Continue reading to obtain an easy step-by-step instructions on developing custom modules for your Drupal 9 website as well as applying CSS assets to those modules.

Drupal 9 Custom Module Development in 5 easy steps

In order to get started with the creation of a custom module in Drupal 9, here are some of the basic steps that you need to follow.

Step 1: Create a custom folder for your module

Create Custom Module & CSS In Libraries In Drupal 9

Step 2: Choose a short name or machine name for your module

Before deciding on a name for your module, here are some crucial guidelines to keep in mind: 

  • It is required to begin with a letter.
  • Only lowercase characters, numerals, and underscores are allowed to be included in it.
  • It is not allowed to have any spaces in it.
  • It cannot be more than 50 characters long at any point.
  • It must be one of a kind. It is important to keep in mind that the short name of your module should not be identical to that of any other module, theme, theme engine, or installation profile that will be used on the site.
  • It should not be any of the following reserved terms: src, lib, vendor, assets, CSS, files, images, js, misc, templates, includes, fixtures, Drupal, or any combination of the three.

We’ll call it the “hello_module” for now.

Step 3: Create a .info.yml file

Your.info.yml file stores the module information, as well as information regarding compatibility and dependencies. It is necessary to generate the.info.yml file in order to offer information for the Drupal Web UI administration pages and to alert Drupal that its presence has been detected in the system. 

The name of the file that we use is hello_module.info.yml.

name: Hello Module

type: module

description: ‘First custom drupal 9 module’

package: custom

core_version_requirement: ^9 || ^10

There are three components that make up the.info.yml file: the key, the separator, and the value.

Where the name is the key, the ‘:’ (colon) serves as the separator, and “Hello Module” is the value.

Step 4: Create a Controller

Controllers are the components of an application that are in charge of controlling the flow of the application as well as its logic. Controllers are responsible for processing user requests and determining the most appropriate next step. They are able to carry out one or more activities and respond with a variety of results in response to a specific request. Our module’s controller is accountable for generating the body and transmitting it back to the page where it was initially requested. 

Now let’s make a file in a directory that’s organized as /src/Controller/WelcomeController.php.

Create Custom Module & CSS In Libraries In Drupal 9

WelcomeController.php is the name of our file.

<?php

namespace Drupal\hello_module\Controller;

class WelcomeController {

 public function welcome() {

$body = “Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, 

when an unknown printer took a galley of type and scrambled it to make a type specimen book. 

It has survived not only five centuries, but also the leap into electronic typesetting,

remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset

sheets containing Lorem Ipsum passages, and more recently with desktop publishing software

like Aldus PageMaker including versions of Lorem Ipsum.”;

    return [

      ‘#markup => $body

    ];

  }

}

Step 5: Create a routing.yml file:

When a URI is requested, the code that should be run to generate the response is specified by a route.

In order to establish routes, a new.routing.yml file must first be generated. Every route has its own unique machine name, which is written in the format my_module_name.route_name (for instance, hello_module.welcome). 

hello_module.welcome:

  path: ‘/welcome’

  defaults:

    _controller: ‘Drupal\hello_module\Controller\WelcomeController::welcome’

    _title: ‘Welcome to techX session’

  requirements:

    _permission: ‘access content’

The general structure of our hello_module modules looks like this:

Create Custom Module & CSS In Libraries In Drupal 9

Lastly, going to the URL /welcome will cause the Controller that you developed to be called, which will then show the body along with the title.

Result:

Create Custom Module & CSS In Libraries In Drupal 9

Attaching libraries to apply CSS

There are a few different approaches one may take when applying CSS to a custom module. One strategy would be to inspect the element in order to look for the class, after which one would apply the CSS to the element. Alternatively, you can make a template, then add your own special class to it, and then direct your attention to only that class. The second method is preferable to the first since it will provide you with your very own special class and there will be no possibility for your modification to be applied to any of the other pages.

In order to generate a library, you will need to make a new file with the name “module_name.libraries.yml” and save it in the folder containing your own module. You are going to need a CSS file in order to write your CSS code in, so create one immediately. Make a folder on your computer named CSS, and then put the “style.css” file inside of it. You will now additionally need to develop a bespoke template for use. Make a personalized template with the name “welcome-body.html.twig” and save it in the templates folder (as demonstrated in the following image).

Attaching libraries to apply CSS

The name of our document is hello_module.libraries.yml.

custom:

  version: 1.x

  css:

    theme:

      css/style.css: {}

As a result, Drupal is currently unaware that this template even exists. In order to make Drupal aware of any customized changes, you will need to create a file with the name “module_name.module” and call hook_theme() for the implementation.

The name of our file is hello_module.module.

function hello_module_theme() {

  return [

    ‘welcome_body’ => [

      ‘template’ => ‘welcome-body’,

      ‘variables’ => [

        ‘body’ => ‘Default body text’

      ]

    ]

  ];

}

The name of our template document is welcome-body.html.twig.

<div class=”welcome-body”>

<p class=”body-text”> {{ body }}</p>

</div>

Now, let’s target the “body-text” class in our template in order to add a red color to the body text of our template.

Our style sheet is called style.css.

.body-text {

  color: red

}

Now you need to call the theme inside our controller and attach the library to it so that the custom template can be invoked.

namespace Drupal\hello_module\Controller;

class WelcomeController {

  public function welcome() {

    $body = “Lorem Ipsum has been the industry’s standard dummy text ever since

    the 1500s, when an unknown printer took a galley of type and scrambled it to

    make a type specimen book. It has survived not only five centuries, but also

    the leap into electronic typesetting, remaining essentially unchanged. It

    was popularized in the 1960s with the release of Letraset sheets containing

    Lorem Ipsum passages, and more recently with desktop publishing software

    like Aldus PageMaker including versions of Lorem Ipsum.”;

    return [

      ‘#theme’ => ‘welcome_body’,

      ‘#body’ => $body,

      ‘#attached’ => [

        ‘library’ => [

          ‘hello_module/custom’,

        ],

      ]

    ];

  }

}

After applying the CSS, the following is the result:

Apply css in drupal 9

Conclusion

Now, in the end, we hope that through this post you were able to learn How To Create a Custom Module & CSS In Libraries In Drupal 9. However, if you are still looking for a Drupal development company that can help you with all the Drupal-related requirements then you should check out Appic Softwares.

You can even hire dedicated Drupal developers from us and let them maintain your Drupal software. So, what are you waiting for?

Contact us now!

Get Free Consultation Now!


    Contact Us

    Consult us today to develop your application.

      Get in touch with us


      Skype Whatsapp Gmail Phone