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

#! code: Drupal 10: Programatically Injecting Context Into Blocks

Context definitions in Drupal are really useful when you want to inject context into your plugins and I have been using them for a little while now. It has made building custom blocks to add content to pages much easier as I don't need to copy the same block of code to find an entity of a particular sort into the block plugin.

One problem I encountered when using this technique was when trying to programatically create and render a block. The problem was that the context wasn't available in the block when it was used in this way, and it took me a little investigation to find out how to put all of the pieces together.

Rendering a block programatically is sometimes a necessity to do when you need the block outside of the block's normal region. You might create a block that collects together the output of a number of blocks, which allows you to template them together in a very precise way. You might also need to print out a block without having to create a region on a page.

There are a few steps involved in getting things working in this way. In this article I will show how to print blocks programatically, and how to do so using context.

To show the problem in detail, let's take an example of a block called UserContextBlock that has a user entity as the available context. This is a custom block, created in a custom module.

Read more

Spinning Code: We Wish We Could Consult Like Sidney Freedman

Image removed.

Major Sidney Freedman was often the perfect psychiatrist at the perfect moment – all consultants wish we were as effective as Sidney. Major Freedman, most often referred to as Sidney, was a recurring character on M*A*S*H who comes to the 4077th a few times a season. Sidney always seems to know what his patients need; he has the perfect thing to say, while being compassionate to whoever he’s there to help (including himself).

Near Perfect Treatments

The breadth of Sidney’s skills are staggering. Sometimes simple talk therapy is all that’s needed. So when Hawkeye’s nightmares become too much Sidney pops in visit for a few sessions. And when Potter fears his surgical technique is fading a conversation with Sidney is all he needs. When everyone at M*A*S*H is stressed by their work load, a few minutes with Sidney and a prescribed bonfire steadies everyone’s nerves.

But when a really tough case comes up, Sidney is still your man. During one episode a wounded bombardier becomes convinced he’s Jesus. Sidney not only provides an emergency diagnosis but puts his career on the line to defend the man. Faced with a highly decorated soldier who is suicidal, Sidney’s quick hypnotherapy session stabilizes him. The show credits Sidney with advancing treatment of “combat fatigue” (we’ll ignore his treatment was standard 30 years before the Korean Conflict and the work of combat medics); we see him around several related patients (eventually including Hawkeye). He even remembers enough of his medical school training to pinch hit as a surgeon and offer up advice on his way out the door.

“Ladies and gentlemen, take my advice: pull down your pants and slide on the ice.”

Sindey Freedman’s best known piece of advice. Oddly fitting in the moments offered.

He even cares for himself with compassion. When patients are mad at him for his care, he knows it is part of them getting better. When he losses a patient, he knows to take a break at the 4077th and write a long letter to Sigmund Freud.

We all want to be Sidney

Everyone who works in consulting wants to be our own version if Sidney. We all want to be the person who knows exactly what’s needed at exactly the right moment. We want say all the right things. Ask the questions to get to the important truths about a project. Laugh when people are funny, then serious when we need to be. We hope to create or find the latest cutting edge solution that will provide exactly support for our client’s problem. And we want to leave them smiling and wanting more of our help.

Of course, unlike Sidney, we do not have a team of writers providing the lines. Our work doesn’t fit into tidy 22 minute episodes. New cutting edge solutions we find often don’t always work as advertised. When we are tired or frustrated, we make mistakes. When we are fresh and well rested, we still make mistakes.

The best we can do is try to follow Sidney’s example. He stays calm under stress. He stays current with his field’s research. Most importantly, he cares about his patients and provides them the best care he knows how. He even remembers to care for himself when suffering from burnout.

M*A*S*H Consulting

If you didn’t know, or can’t guess from context, my wife and I are M*A*S*H fans. We grew up with it. We bought the DVDs as they Fox released them. It’s our go-to for something comforting to watch. It’s entertaining, and full of great lines and moments to borrow for life examples. As part of marking the show’s 50th anniversary this is part of a short series of posts using consulting lessons from characters in M*A*S*H.

The post We Wish We Could Consult Like Sidney Freedman appeared first on Spinning Code.

The Drop Times: Drupal Best Integrates WebGIS with CMS: Italo Mairo

The Drop Times (TDT) approached Italo Mairo for an interview, asking questions about his work, and he was kind enough to reply via email. His answers inspire any Free Libre and Open-Source Software contributors in general and aspiring Drupal contributors in particular. It would also appeal to young engineers passionate about engineering drawing, computer graphics and visualisation. Read on to grab a bite from the exciting conversation.

Niels de Feyter: Maximize Productivity and Success as a Drupal Contractor: 6 Expert Tips

Working as a Drupal contractor can be rewarding and fulfilling, but it also comes with its own set of challenges. In this article, we'll explore 6 tips for boosting productivity and success as an independent contractor. From setting clear goals and priorities to staying organized and keeping your skills up-to-date, these tips can help you be more efficient and effective in your work. We'll also discuss the importance of networking and building relationships, as well as how to negotiate fair and reasonable rates for your services. By following these tips, you can set yourself up for success and enjoy a fulfilling career as an independent Drupal contractor.

Aten Design Group: How to Use Cypress for Testing Drupal

How to Use Cypress for Testing Drupal Image removed.jenna Fri, 01/27/2023 - 11:19 Drupal Automated Testing

If you’re not including tests in your Drupal development, chances are you think that it adds complexity and expense without providing enough benefit. Cypress is easy to learn and implement, will protect against regression as your projects become more complex and can make your development process more efficient.

Cypress is a tool for reliably testing anything that runs in a web browser. It’s open source and web platform agnostic (think: great for testing projects using front-end technologies like React) and highly extensible. It’s an increasingly popular tool and was the “#1 tool to adopt” according to Technology Radar in 2019.

In this blog, I’ll cover three topics to help you start testing in your Drupal project using Cypress:

  • Installing Cypress
  • Writing and running basic tests using Cypress
  • Customizing Cypress for Drupal

Installing Cypress

Let’s assume that you created your Drupal project using composer as recommended on Drupal.org:

$ composer create-project drupal/recommended-project cypress

Your project will have (at least) this basic structure:

vendor/   web/   .editorconfig   .gitattributes   composer.json   composer.lock

The cypress.io site has complete installation instructions for various environments; for our purposes we’ll install Cypress using npm.

Initialize your project using the command npm init. Answer a few questions that node.js asks you and you’ll have a package.json file that looks something like this:

{   "name": "cypress",   "version": "1.0.0",   "description": "Installs Cypress in a test project.",   "main": "index.js",   "scripts": {   "test": "echo \"Error: no test specified\" && exit 1"   },   "author": "",   "license": "ISC"   }

Now you’re ready to install Cypress in your project:

npm install cypress --save-dev

Let’s run Cypress for the first time:

npx cypress open

Since we haven’t added any config or scaffolding files for Cypress, it will observe It looks like this is your first time using Cypress and open the Cypress app to the welcome screen, showing both E2E Testing and Component Testing as “Not Configured”. Let’s configure your project for E2E testing: click the “Not Configured” button for E2E Testing. Cypress will report that it added some files to your project:

cypress/   node_modules/   vendor/   web/   .editorconfig   .gitattributes   composer.json   composer.lock   cypress.config.js   package-lock.json   package.json

Click on “Continue”, then choose your preferred browser for testing and click “Start E2E Testing in [your browser of choice]”.

In a separate window, Chrome will open to the Create your first spec page:

Image removed.

Click on the ‘Scaffold example specs’ button and Cypress will create a couple of folders with example specs to help you understand a bit more about how to use Cypress. Read through them in your code editor and you’ll find that the language (based in js) is intuitive and easy to follow; click on any in the Chrome test browser and you’ll see two panels: a text panel on the left, showing each step in the active spec and a simulated browser window on the right, showing the actual user experience as Cypress steps through the spec.

Open the cypress.config.js file in your project root and change it as follows:

const { defineConfig } = require("cypress");     module.exports = defineConfig({   component: {   fixturesFolder: "cypress/fixtures",   integrationFolder: "cypress/integration",   pluginsFile: "cypress/plugins/index.js",   screenshotsFolder: "cypress/screenshots",   supportFile: "cypress/support/e2e.js",   videosFolder: "cypress/videos",   viewportWidth: 1440,   viewportHeight: 900,   },   e2e: {   setupNodeEvents(on, config) {   // implement node event listeners here   },   baseUrl: "https://[your-local-dev-url]",   specPattern: "cypress/**/*.{js,jsx,ts,tsx}",   supportFile: "cypress/support/e2e.js",   fixturesFolder: "cypress/fixtures"   },   });

Change the baseUrl to your project’s url in your local dev environment.

These changes tell Cypress where to find its resources and how to find all of the specs in your project.

Writing and running basic tests using Cypress

Create a new directory called integration in your /cypress directory, and within the integration directory create a file called test.cy.js.

cypress/   ├─ e2e/   ├─ fixtures/   ├─ integration/   │ ├─ test.cy.js   ├─ support/   node_modules/   vendor/   web/   .editorconfig   .gitattributes   composer.json   composer.lock   cypress.config.js   package-lock.json   package.json

Add the following contents to your test.cy.js file:

describe('Loads the front page', () => {   it('Loads the front page', () => {   cy.visit('/')   cy.get('h1.page-title')   .should('exist')   });   });     describe('Tests logging in using an incorrect password', () => {   it('Fails authentication using incorrect login credentials', () => {   cy.visit('/user/login')   cy.get('#edit-name')   .type('Sir Lancelot of Camelot')   cy.get('#edit-pass')   .type('tacos')   cy.get('input#edit-submit')   .contains('Log in')   .click()   cy.contains('Unrecognized username or password.')   });   });

In the Cypress application when you click on test.cy.js you’ll watch each of the test descriptions on the left while Cypress performs the steps in each describe() section.

This spec demonstrates how to tell Cypress to navigate your website, access html elements by id, enter content into input elements and submit the form. (I discovered that I needed to add the assertion that the element contains the text ‘Log in’ before the input was clickable. Apparently the flex styling of the submit input was impeding Cypress’ ability to “see” the input, so it couldn’t click on it.)

Customizing Cypress for Drupal

You can write your own custom Cypress commands, too. Remember the supportFile entry in our cypress.config.js file? It points to a file that Cypress added for us which in turn imports the './commands' file(s). (Incidentally, Cypress is so clever that when importing logic or data fixtures you don’t need to specify the file extension: import './commands', not './commands.js'. Cypress looks for any of a dozen or so popular file extensions and understands how to recognize and parse each of them.)

But I digress.

Define your custom commands in this commands.js file, such as:

/**   * Logs out the user.   */   Cypress.Commands.add('drupalLogout', () => {   cy.visit('/user/logout');   })     /**   * Basic user login command. Requires valid username and password.   *   * @param {string} username   * The username with which to log in.   * @param {string} password   * The password for the user's account.   */   Cypress.Commands.add('loginAs', (username, password) => {   cy.drupalLogout();     cy.visit('/user/login');   cy.get('#edit-name')   .type(username);   cy.get('#edit-pass').type(password, {   log: false,   });   cy.get('#edit-submit').contains('Log in').click();   });

Here we’re defining a custom Cypress command called drupalLogout(), which we can use in any subsequent logic – even other custom commands. To log a user out, call cy.drupalLogout(). This is the first thing we’re doing in our custom command loginAs, in which the first thing we do is ensure that Cypress is logged out before attempting to log in as the user specified by the username and password parameters.

Using environment variables you can even define a Cypress command called drush() – using some helper functions – with which you can execute drush commands in your test writing or custom commands. How simple is this for defining a custom Cypress command that logs a user in using their uid?

/**   * Logs a user in by their uid via drush uli.   */   Cypress.Commands.add('loginUserByUid', (uid) => {   cy.drush('user-login', [], { uid, uri: Cypress.env('baseUrl') })   .its('stdout')   .then(function (url) {   cy.visit(url);   });   });

This uses the drush user-login command (drush uli for short) and takes the authenticated user to the site’s base url.

Consider the security benefit of never having to read or store user passwords in your testing. Personally I find it amazing that a front-end technology like Cypress can execute drush commands, which I have always thought of as being very much on the back end.

You’ll want to familiarize yourself with Cypress fixtures as well (fixtures are files that hold test data) - but that’s a little outside the scope of this post. Please see Aten’s webinar Cypress Testing for Drupal Websites, particularly the section on fixtures that begins at 18:33. That webinar goes into greater detail about some interesting use cases – including an ajax-enabled form - and includes a scene from Monty Python and the Holy Grail which I hope you enjoy.

Because our VP of Development, Joel Steidl, helped me define drush() as a custom Cypress command, I’d like to share that with you as well. Please feel free to use or fork Aten’s public repository on Cypress Testing for Drupal.

Happy testing!

Image removed.Jordan Graham