DrupalEasy: DrupalEasy Podcast S14E6 - Ryan Price - How to start a Drupal project the right way

We talk with Ryan Price about how to start a new Drupal project the right way, including development environment setup, code base setup, initial modules, Git setup, and common newbie mistakes.

URLs mentioned

DrupalEasy News

Audio transcript

We're using the machine-driven Amazon Transcribe service to provide an audio transcript of this episode.

Subscribe

Subscribe to our podcast on iTunes, Google Play or Miro. Listen to our podcast on Stitcher.

If you'd like to leave us a voicemail, call 321-396-2340. Please keep in mind that we might play your voicemail during one of our future podcasts. Feel free to call in with suggestions, rants, questions, or corrections. If you'd rather just send us an email, please use our contact page.

Matt Glaman: The trinary states of Drupal access control: allowed, forbidden, neutral.

One of my favorite features of Drupal is the user access control experience. Drupal has a robust permission and role (access control list) API that allows for fine-tuned control of what users can and cannot do. Drupal developers end up interacting with Drupal's access system in one way or another. Every project has some request to enhance or alter how normal access works. When this happens, some modules (see Field Permissions) provide no-code solutions for the end user. Other times the developer taps into Drupal hooks and writes code to adjust the access result.

A common use case I have experienced is allowing content from a specific content type to be accessible to privileged users (like paywalled content.) Drupal core doesn't provide granular permissions for viewing the content of specific content types. You need to extend Drupal and use the hook_node_access hook to alter the default user access.

Specbee: How to Create a Custom Module and add CSS Libraries in Drupal 9

How to Create a Custom Module and add CSS Libraries in Drupal 9 Nitin Lama 31 Jan, 2023 Subscribe to our Newsletter Now Subscribe Leave this field blank

There are thousands of Drupal core and contributed modules to choose from, so why would anyone still want to build custom modules? The majority of the time it’s because website builders are looking for customized features to achieve specific functionalities or to stand out from the competition. For components that aren’t commonplace, a contributed or a core module does not always meet exact requirements. That’s when custom module development comes into play. 

Thanks to Drupal’s flexibility, you can now create powerful custom modules to add functionality and logic to meet your unique business requirements. Read on to find an easy step-by-step guide on custom module development and also applying CSS assets on your Drupal 9 website.

Image removed.

Drupal 9 Custom Module Development in 5 easy steps

Here are some essential steps you need to follow to get started with creating a custom module in Drupal 9.

Step 1: Create a custom folder for your module

 

Image removed.

Drupal 9 file structure

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

Some important rules to follow before you choose a name for your module: 

  • It must start with a letter.
  • It must contain only lowercase letters, digits, and underscores.
  • It must not contain any spaces.
  • It must not be longer than 50 characters.
  • It must be unique. Your module should not have the same short name as any other module, theme, theme engine, or installation profile you will use on the site.
  • It should not be any of the reserved terms: src, lib, vendor, assets, CSS, files, images, js, misc, templates, includes, fixtures, or Drupal.

Let's name it: “hello_module”.

Step 3: Create a .info.yml file

Your .info.yml file holds the module information, compatibility, and dependencies information. The .info.yml file is created to notify Drupal about its existence in the system and provide information for the Drupal Web UI administration pages. 

Our file name: hello_module.info.yml

name: Hello Module type: module description: 'First custom drupal 9 module' package: custom core_version_requirement: ^9 || ^10

The .info.yml file comprises 3 things: key, separator, value.
Where the key is the name, the separator is ‘:’ (colon) and the value is “Hello Module”.

Step 4: Create a Controller

Controllers are responsible for controlling the flow of the application and its logic. Controllers process user requests and determine the appropriate course of action. They can perform one or more actions and return different results to a particular request. The controller in our module is responsible for generating the body and sending it back to the page. 

Now let’s create a file in a folder structured as /src/Controller/WelcomeController.php

Image removed.

 

Our file name: WelcomeController.php

<?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:

A route specifies the code that should be executed to generate the response when a URI is requested.

The .routing.yml file is created to define routes. Each route is defined as a machine name in the form of my_module_name.route_name (for example 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'

This is how our overall hello_module module structure looks like:

Image removed.

 

Finally, visiting /welcome will call the Controller that you created and will display the body with the title.

Result:

Image removed.

Attaching libraries to apply CSS

There are multiple ways to apply CSS to a custom module. One way would be to search for the class by inspecting the element and then applying the CSS to it. Another way is  to create a template and add your own unique class and target that specific class. The latter is a better way than the former as you’ll have your own unique class and there will be no way that your change will apply to some other pages.

To create a library you need to create a new file as “module_name.libraries.yml” and place it in your custom module folder. You now need a CSS file in which you will write your CSS code. Create a folder called CSS and place “style.css” inside that folder. Now you will also need to create a custom template. Create a custom template as “welcome-body.html.twig” and place it inside the templates folder (as shown below).

Image removed.

 

Our file: hello_module.libraries.yml

custom: version: 1.x css: theme: css/style.css: {}

So now, Drupal doesn’t know that this template exists. To let Drupal know, you need to create a “module_name.module” file for any custom changes and use hook_theme() for the implementation.

Our file name: hello_module.module

function hello_module_theme() { return [ 'welcome_body' => [ 'template' => 'welcome-body', 'variables' => [ 'body' => 'Default body text' ] ] ]; }

Our template file: welcome-body.html.twig

{{ body }}

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

Our CSS file: style.css

.body-text { color: red }

Now, you need to attach the library to our controller and call the theme inside it so that the custom template is called.

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', ], ] ]; } }

Here’s the result after applying the CSS:

Image removed.

Final Thoughts

Flexibility to create custom modules that add specific functionality unique to a business requirement is one of Drupal’s power features. Custom modules allow you to extend Drupal’s core functionality and add new features and logic to a website. We hope this article will help you create your first custom module on Drupal 9. If you found this useful, consider subscribing to our weekly newsletter where we churn out great stuff every week and send it straight to your inbox!

If you’re looking for a Drupal development agency that can help you build custom modules to accommodate your growing business needs, we’d love to talk!

Author: Nitin Lama

Meet Nitin Lama, a backend Drupal Developer at Specbee who believes progressing one day at a time could go a long way. Swimming is his hobby, but he’s a huge music lover and enjoys producing and exploring new music. Music and cooking act as therapy for him. Space and tech are his best conversation starters when meeting new people. If dreams came true, he’d be traveling to a Voyager station!

Email Address Subscribe Leave this field blank Drupal 9 Drupal 9 Module Drupal Development Drupal Planet

Leave us a Comment

 

Recent Blogs

Image Image removed.

How to Create a Custom Module and add CSS Libraries in Drupal 9

Image Image removed.

How to create and apply a patch with Git Diff and Git Apply commands for your Drupal website

Image Image removed.

Installing Drupal 9 on Windows Subsystem for Linux from Scratch

Want to extract the maximum out of Drupal? TALK TO US

Featured Success Stories

Image removed.

A Drupal powered multi-site, multi-lingual platform to enable a unified user experience at SEMI.

Image removed.

Discover how our technology enabled UX Magazine to cater to their massive audience and launch outreach programs.

Image removed.

Discover how a Drupal powered internal portal encouraged the sellers at Flipkart to obtain the latest insights with respect to a particular domain.

VIEW ALL CASE STUDIES

Talking Drupal: Talking Drupal #384 - The Drop Times

Today we are talking about The Drop Times with Anoop John.

For show notes visit: www.talkingDrupal.com/384

Topics
  • Tell us about the Drop Times
  • Tell us a bit about yourself
  • Getting involved with Drupal
  • People behind Drop Times
  • Mission of the Drop Times
  • Content source
  • Current audience
  • Attribution issues
  • How has the beginning been
  • Funding
  • Roadmap
  • Non-profit
  • Contribution of content
  • How can we help
Resources Guests

Anoop John - zyxware.com @anoopjohn

Hosts

Nic Laflin - www.nLighteneddevelopment.com @nicxvan John Picozzi - www.epam.com @johnpicozzi Katherine Druckman - katherinedruckman.com @katherined

MOTW Correspondent

Martin Anderson-Clutz - @mandclu Content Planner Helps you to create, plan and manage content. It offers a dashboard, a content calendar and a todo list.

Palantir: Paak's DrupalEasy Fellowship Experience: An opportunity to learn, work within, and contribute to Drupal

Internships and Fellowships

In this first part of a four-part series, Paak talks about his background, the projects he’s worked on, and the vision for his professional future

There is no one way to change a career path. Palantir.net’s four most recent fellows - Paak, Tessa, Travis, and Yang - all joined us through the DrupalEasy program. With their different professional backgrounds and experiences, each offers a unique perspective into what interested them in Drupal and their journey to becoming integral members of Palantir.net.

In each of their written entries they share, among other insights, how they have each adjusted to a fully-remote workplace, how their own skills supported their success as a Fellow, and the importance of Palantir.net’s culture which encourages asking questions, remaining curious, and reaching out for help.

This is Paak's story.

 

Where I Started

Growing up, I was the person in the family that always had to fix things in the home. In a household that always had at least seven people, there was definitely always something that needed to be fixed. The enjoyment of learning and fixing things led to my first job where I worked at a computer cafe, learning both how to properly build computers and the intricacies of network security.

This experience made me realize how much I enjoyed fixing and creating things, so my next decision was to attend automotive school to become an auto mechanic. Although I loved being a mechanic, I always had an itch to learn more about the tech world; the fact that it is ever changing provided me with the opportunity to both fix and create, and the fast paced environment intrigued me.

So, looking for the best of both worlds - automotive and tech - I pursued a job working for a start-up company that helped people buy and sell cars. It was here where I honed my skills in website building, while learning the ins and outs about web development. Throughout my time there, I found I had a much greater interest in planning, designing, and building the website than I did in any other aspect of my position. This is where my true interest in website development was born - and fortunately for me, I was soon introduced to the Drupal community and the DrupalEasy program. 

I decided now was the time, and I applied for the DrupalEasy scholarship. After meeting Mike Anello, the lead instructor and curriculum developer, I felt assured that I would be able to learn and master the main fundamentals of Drupal. He was absolutely right. 

I am fortunate enough to have spent the last year with Palantir.net, and may not be here today without the pathway provided through the Fellowship option I was awarded. It provided me with the opportunity to attend the DrupalEasy course, and that changed my professional trajectory and opened doors I never thought possible.

How has my experience been so far? Well, Palantir.net has supported, encouraged, and nurtured my continuous growth and professional development, which inspires me to keep learning more about Drupal and web development. It keeps me excited to learn more every day.

Where I Am Now

If somebody asked me five years ago what I thought I’d be doing now, I probably would have said I’d be working in the automotive industry and, possibly, learning about technology. I’ve always been interested in advancements and progress that could have a positive impact in the future. Ultimately, my aim was to learn as much as possible so I could teach younger generations about what I’ve learned so they can advance themselves and contribute in their own creative and fundamental way.

Having the opportunity to learn, work within, and contribute to Drupal has reinforced my belief that it will continue to play a huge part in web development and will enhance the lives of others.

Palantir.net has given me the opportunity to learn different aspects of Drupal, including front-end and back-end development, behat testing, and more. My goal is - and has always been - to learn as much as I can; beginning as an engineer and working my way up to become a senior developer. 

While I’m unsure if I’ll be a front-end or back-end developer, I do know that I will reach a professional point where I am able to show others what I do and how my skills have helped me achieve my goals. My best hope is that it will encourage, inspire, and invigorate folks to contribute to and help build the Drupal community. 

Community Culture Drupal People