Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 80

Table of Contents

1 Installing, Administration & getting started with Drupal..................................................................3


1.1 Drupal as a Content Management System..............................................................................3
1.2 Background of Drupal..............................................................................................................4
1.3 Requirements...........................................................................................................................5
1.3.1 Server Requirement.............................................................................................................5
1.4 Software Requirement.............................................................................................................6
1.4.1 Supported Browsers............................................................................................................6
1.4.2 PHP extensions....................................................................................................................6
1.5 Additional Tools........................................................................................................................6
1.5.1 Drush....................................................................................................................................6
1.5.2 Git.........................................................................................................................................6
1.5.3 Composer.............................................................................................................................7
1.5.4 Devel....................................................................................................................................7
1.6 Installation................................................................................................................................7
2 Concepts of Drupal..........................................................................................................................15
2.1 Page........................................................................................................................................15
2.2 Article.....................................................................................................................................18
3 Drupal Structure and Site Organization...........................................................................................20
3.1 Creating and Managing Menus..............................................................................................20
3.2 Managing Taxonomy..............................................................................................................21
4 Managing Media..............................................................................................................................27
4.1 Image Styles...........................................................................................................................27
4.2 Working with Layout..............................................................................................................30
4.3 Blocks.....................................................................................................................................33
5 Working with Advanced Content.....................................................................................................35
5.1 Working with Forms and Fields..............................................................................................35
5.2 Creating New Content Types.................................................................................................35
5.3 Adding Interaction with Queries............................................................................................40
6 System and Site Configuration.........................................................................................................41
6.1 System Settings and Configuration........................................................................................41
6.1.1 Reports...............................................................................................................................41
6.1.2 People................................................................................................................................42
6.1.3 Structure............................................................................................................................42
6.1.4 Configuration.....................................................................................................................43
6.2 Working with the User Interface............................................................................................44
6.3 Managing Media....................................................................................................................44
6.4 Indexing, Metadata and Locale Configuration.......................................................................46
7 User and Access Control..................................................................................................................46
7.1 Users and Roles......................................................................................................................46
7.2 User Permissions....................................................................................................................48
8 Drupal Modules...............................................................................................................................52
8.1 Finding Modules.....................................................................................................................53
9 Drupal Themes.................................................................................................................................56
9.1 Distributions...........................................................................................................................56
9.2 Configuring the Theme...........................................................................................................56
9.3 Regions in a Theme................................................................................................................58
9.4 Working with Custom Themes...............................................................................................60
10 PHP OOP.....................................................................................................................................60
10.1 What is OOP?.........................................................................................................................60
10.2 What are Classes and Objects?..............................................................................................61
10.3 Passing Arguments by Reference...........................................................................................63
10.4 Annotation.............................................................................................................................65
11 Twig.............................................................................................................................................66
11.1 Variables.................................................................................................................................67
11.2 Comments..............................................................................................................................67
11.3 Filters......................................................................................................................................68
12 Composer....................................................................................................................................69
12.1 Package installation................................................................................................................69
12.2 Installation - Windows...........................................................................................................70
13 Custom Theme Development....................................................................................................70
13.1 Getting Started with Custom Drupal 8 Theme Development................................................70
14 Custom Module Development..................................................................................................77
14.1 Getting started with Module development in Drupal 8........................................................77
14.2 Forms......................................................................................................................................79
14.3 Plugins....................................................................................................................................80

Drupal developers training minimal content


Objective
Using Drupal's core themes
Creating a custom Drupal theme
Drupal's templating system
Adding CSS and Javascript to your Drupal theme
Twig syntax and Twig debug
Sub-theming with Bootstrap, etc.
Using Twig to customize Views output
Preprocess functions
Extending Twig templates
Using libraries to manage internal and external assets

1 Installing, Administration & getting started with Drupal

1.1 Drupal as a Content Management System


What is a content management system?
A content management system (CMS) is a software tool that lets users add, publish,
edit, or remove content from a website, using a web browser on a smartphone, tablet,
or desktop computer. Typically, the CMS software is written in a scripting language,
and its scripts run on a computer where a database and a web server are installed. The
content and settings for the website are usually stored in a database, and for each page
request that comes to the web server, the scripts combine information from the
database and assets to build the pages of the website.

The combination of the operating system that the CMS runs on, the scripting language
it is written in, the database it stores its information in, and the web server that runs
the scripts to retrieve information and return it to the site visitor’s web browser is
known as the stack that the CMS runs on. This stack is mainly composed of an
Apache Web server with MySQL database and PHP scripting language and
collectively known as AMP Stack. This AMP stack could be configured on Windows,
Linux and Mac operating systems.

What is Drupal?
Drupal is a flexible CMS based on the LAMP stack, with a modular design allowing
features to be added and removed by installing and uninstalling modules, and
allowing the entire look and feel of the website to be changed by installing and
uninstalling themes. The base Drupal download, known as Drupal Core, contains the
PHP scripts needed to run the basic CMS functionality, several optional modules and
themes, and many JavaScript, CSS, and image assets. Many additional modules and
themes can be downloaded from the Drupal.org website.

1.2 Background of Drupal


The name Drupal was derived from the English pronunciation of the Dutch word
"druppel," which means "drop.". The Co-founders of Drupal are Dries Buytaert and
Hans Snijder on the year of 2001GC. For it’s symbol, the stylised a Druplicon with
eyes, curved nose and a mischievous smile.

Why Drupal?
Drupal is the preferred choice for government agencies, large associations, nonprofits,
and many Fortune 500 companies. Simple for editors, powerful for administrators,
secure, and accessible for everyone else. Drupal is well suited for complex, content
heavy, and high traffic websites, as well as those with large resource libraries and
databases. Some of the advantages of using Drupal are:-
 Powerful functionality for developer
 Flexible content architecture
 Powerful in-site search
 flexible integration
 Highly scalable
 Robust Security

Who Uses Drupal?


 NASA https://nasa.gov
 RedHat https://redhat.com
 OXFAM https://oxfam.org
 London https://london.gov.uk
 U.S. Department of Commerce https://commerce.gov/
 UN https://un.org/en/
 CVS Health https://cvshealth.com

Drupal Statistics
 2.3% websites on the internet run on drupal
 drupal accounts 4.7% of CMS
 more than 47,300 modules
 more than 2950 themes
 more than 1350 distributions
 more than 1 million websites run drupal
 available in 100 languages
1.3 Requirements
1.3.1 Server Requirement
1.3.1.1 Disk space
The total amount of disk space needed for your site is not a fixed amount, as it
depends on your site. The base files for the core software take up about 100 MB on
the web server. You will need more space if you install additional modules or themes,
and you’ll also need space for media, backups, and other files generated by and
uploaded to your site.

1.3.1.2 PHP
PHP 7.4 or a higher PHP 7 version. PHP must be set up with a minimum memory size
of 64MB.

1.3.1.3 Web server


Apache (Recommended)
Apache is the most commonly used web server. The core software will work on
Apache 2.4.7 or higher hosted on UNIX/Linux, OS X, or Windows that have the
Apache mod_rewrite module installed and enabled. The Apache VirtualHost
configuration must contain the directive AllowOverride All to allow the .htaccess file
to be used.

Nginx
Nginx is a commonly used web server that focuses on high concurrency, performance
and low memory usage. The core software will work on Nginx 0.7 or greater hosted
on UNIX/Linux, OS X, or Windows. The ngx_http_rewrite_module must be installed
and enabled.

Microsoft IIS
Microsoft IIS is a web server and set of feature extension modules for use with
Microsoft Windows. The core software will work with IIS 5, 6, 7, 8, or 10 if PHP is
configured correctly. Because clean URLs are required, you may need to use a third
party product. For IIS 7/8, you can use the Microsoft URL Rewrite module or a third
party solution.

1.3.1.4 Database
MySQL - 5.7.8 (MariaDB 10.3.7, Percona 5.7.8) or higher with an InnoDB-
compatible primary storage engine
PostgreSQL - 10.0 or higher with the pg_trgm extension
1.4 Software Requirement
1.4.1 Supported Browsers
 Desktop browsers:
 Google Chrome
 Firefox
 Safari
 Microsoft Edge
 Opera
 Mobile browsers:
 Safari for iOS
 Chrome for Android
 Chrome for iOS
 UC Browser
 Opera Mini (except for 'extreme data savings' mode)
 Samsung Internet

1.4.2 PHP extensions


 PHP PDO
 PHP MySQLi or PHP PgSQL
 PHP XML
 PHP GD
 PHP OpenSSL
 PHP JSON
 PHP cURL
 PHP Mbstring

1.5 Additional Tools


1.5.1 Drush
Drush is a command-line tool for building and maintaining sites, providing an
alternative to using the administrative interface for many operations. If you want to
use Drush, you will need to have command-line terminal access to the server where
your website will be hosted, and you will need to have a compatible version of the
Drush tool installed on that server.

1.5.2 Git
Git is a version control system you can use to track changes made to files within your
entire site, or files relating only to the module or theme that you are using. Git makes
it possible to try out changes, and if necessary, revert to a previous version. It can be
used as well to track changes in the configuration files and synchronize the
configuration of different sites. Git has become the standard for web development
projects.
1.5.3 Composer
Composer is a tool for managing PHP dependencies, where the developer specifies
what version of each external library is needed, and Composer manages the process of
downloading and installing the libraries. The core software is a primary user of
Composer, because it makes use of several externally-developed software libraries,
which must be downloaded and installed in order for the core software to work.

1.5.4 Devel
The contributed Devel module helps with development tasks such as debugging and
inspecting code, analyzing database queries, and generating dummy content.

1.6 Installation
Installation Methods
Manual Download
This can be done by downloading the core project from the main website that is
available at drupal.org/project/drupal. The website will contain a list of actively
supported versions which can be downloaded and installed. However, it is always
recommended to download the latest version which at the time of writing this
document is based on the 9.x family. This method is the traditional approach to install
Drupal.

Using Composer
If you are building a site that might use modules with complicated dependencies, you
should use Composer to download the core software, because Composer will manage
the dependencies properly. Composer is supported on Drupal 8.6 and higher by
default and you need to initialize it if your project is not based on composer.

Using Pre-configured Environment


Use a pre-configured environment or virtual machine that contains Drupal and all the
required supporting software to install Drupal locally such as a bitnami stack or
docker environment. 

Preparing to install
We will use the manual download method for the installation of Drupal in a typical
environment. The steps to do so are listed below.
Step 1: Choose your desired version from https://drupal.org/project/drupal 
Step 2: Click the version you wish to download under Recommended releases to
download the core. The difference between the two types of download is in their file:
one is based on tar while the other is zip compression.

Step 3: Upload the downloaded file into your web hosting directory.
Step 4: Extract the compressed folder into the root directory of your hosting. Use
tools such as WinRaR and 7-Zip on windows to extract the files. If you are on a linux
server, you can use tar command as follows. The third parameter specifies for the file
and might be different based on the version that you have downloaded.
tar -xzf drupal-9.2.0.tar.gz

Step 5: Rename your directory to match your web hosting configuration or


reconfigure your web hosting so that the directory name matches the directory your
web hosting is configured to use for your site.
Running the Installer
Step 1: open a web browser and navigate to the URL of the web hosting’s root
directory followed by the folder name if it is not on the root directory.
Step 2: The installation page appears prompting you to choose language from the list
of available languages. English is the recommended one thus proceed with it by
clicking on save and continue.

Step 3: Now the screen appears with a list of installation profiles. Installation profiles
provide site features and functions for a specific type of site as a single download
containing the core software, contributed modules, themes, and pre-defined
configuration. Core contains two installation profiles. Select the core Standard
installation profile. Click Save and continue.
Step 4: The next step in the installer will verify that your system meets the minimum
requirements. If it does not, you will be presented with an outline of what needs to be
corrected in order to proceed. If it does, the installer will automatically advance to the
next step.
Step 5: Now it will ask for the database information. If you have not created a
database for Drupal then create it now using phpmyadmin or the command line. Once
you have created the database, you can now provide the database information along
with credentials in the form as per the attached image below.
Step 6: If your database server is in a separate machine than the application server,
then you can configure that in Advanced Options. By default Drupal assumes that the
database server will be on the same machine as the web server that is the localhost.
Moreover, if you are not using standard ports for the database, you can also specify
the port in which the database is running. The default port for MySQL, MariaDB and
it’s alike is 3306. Nevertheless, in a typical shared hosting environment you might
have a limited number of databases thus you would have access only to a single
database and for this situation you can use a table prefix.
Step 7: The next step will display a progress bar under the heading Installing Drupal.
After the installer has completed, it will automatically advance to the next step.

Step 8: The final step is to configure some basic information about your new site.
Note that the user account you create in this step is the site’s admin account. You can
safely name this account something that is composed of alphabets and numbers for
security purpose, and make sure to choose a strong password with a combination of
upper and lower cases, number and special characters. You need to configure the site
name along with administrator email address and password for the site admin. The
remaining fields can likely be left at their default values.
Step 9: You will be redirected to the front page of your new site and you should see
the message Congratulations, you installed Drupal! displayed at the top of the page.

Your installation is now complete.

Exploring Drupal
The toolbar provided by the core Toolbar module displays the Manage administrative
menu at the top or left side of the site, for users with permission to see it. This menu
provides access to all of the administrative areas of the site. The menu entries will
vary depending on which modules are active on your site and the permissions of the
person viewing the menu; if you install using the core Standard installation profile
and have full administrative permissions, the top-level entries are as follows:

Content

Lists and manages existing content, and allows creation of new content.

Structure

 Contains a list of links for managing structural elements of the site, such as: blocks, content
types, menus, and taxonomy.

Appearance

 Manages themes and appearance-related settings.

Extend

 Manages the installation and uninstallation of modules

Configuration

 Contains links to settings pages for various site features.

People

 Manages users, roles, and permissions.

Reports
 Contains links to logs, update information, search information, and other
information about the site’s status.
Help Lists help topics for installed modules that provide them. The arrow button on
the far right side of the second line of the toolbar can be used to switch the menu from
appearing horizontally at the top of the page, to a vertical format on the left side.
When viewed vertically, the menu becomes an interactive tree.

Contextual Links
Some administrative and editing functionality on the site can be accessed through the
contextual links displayed by the core Contextual Links module. Contextual links take
you to some of the same pages that you can access through the administrative menu,
but instead of having to navigate through the menu hierarchy, these links are provided
near where the related content is displayed on your site.
Contextual links have to be activated to be visible. If your site’s theme uses the
default styling for contextual links, a pencil icon is used to indicate that contextual
links are present and activated, and if you click the icon, you will see the contextual
links.
2 Concepts of Drupal
2.1 Page
Pages are usually reserved for content that will remain static indefinitely. While the
content can be changed to suit the site’s purpose, these pages are usually always
located in the same area. For example, an “About Us” area is most likely saved as a
page. Contact forms, services pages, terms of service agreements and the like are also
included.
We will study about how to Create Pages in Drupal. It is very easy to create pages in
Drupal. Following are the simple steps used to create pages in Drupal.

Step 1 − Click on Content and then on Add content as shown in the figure below

Step 2− Click the Basic page option.

Step 3− Create Basic page will get displayed where you need to fill all the required
details as shown in the following screen.
Following are the details of the fields present on Create Basic page.
Revision Log messages − It specifies to provide revise information, if any changes are
made in the pages.
Title − It specifies the title for new page.
Summary - Summary of the value of the body field. Can be used as teaser in overview
pages
Body − It specifies the description of the page.
Text format − It specifies the Text format for your page such as Filtered HTML, Full
HTML, and Plain text.
Menu settings − By clicking on checkbox Provide a menu link, it shows the details of
Menu such as Menu link title, Description, Parent item,
URL alias – to specify an alternative path by which this data can be accessed. For
example, type "/about" when writing an about page.
Authoring Information - to specify author and authored date.
Promotion Options
Promote to front page – to make the page available on the front page.
Sticky at top of lists – to stick the page at the top, even if there are other latest pages.
Once you complete adding the content to the page. Click the Save button to create the
page. Before saving the details, you can also preview the filled page using
the Preview button.
2.2 Article
What are articles?
Articles are posts that relate more to how blogs and news releases behave. It’s the part
of the site that is in constant motion as more content is added regularly. Think of it
this way. When you visit a news website and read the story, that is an article.
Following are the steps used to create articles in Drupal.

Step 1 − Click on Content and then on Add content as shown in the figure below

Step 2 − you will get the pop-up window as shown in the following screen.
Select Article.
Step 2 − you will get the following screen.

Below are the fields present in Create Article page.


Title − It specifies the title for new article.
Tags − Describes the content of your article. Tags contain those related words which
are included into your articles.
Body − Enter the description.
Text format − It specifies the Text format such as Filtered HTML, Full
HTML and Plain text.
Image − Upload images by choosing a particular file.
When you click choose file, a pop-up window appears, you can select an image from
your local file, once you choose a file, click Upload. The image gets uploaded.
Menu settings − By clicking on Provide a menu link checkbox it shows all the related
details of Menu such as Menu link title, Description, Parent item, and Weight.
Comment settings − By selecting open or close, it allows others to write comment
for the article.
Revision information − Provides revised information if any changes are made in the
article.
URL ALIAS settings − Add URL alias to access the content of article to the users.
Authoring information − Specifies the authored name and the date when article has
been authored.
Publishing options − Allows options for articles to be Published, Promoted to front
page and Sticky at top of lists for the users.
After filling all the details about the article, click the Save button.

3 Drupal Structure and Site Organization


3.1 Creating and Managing Menus
What is a menu?
Module provides an interface to control and customize the menu system. Menus are
primarily displayed as a hierarchical list of links. By default, new menu links are
placed inside a built-in menu labeled Main navigation, but administrators can also
create custom menus.
The core Standard installation profile contains five menus:
Main navigation
Links to sections intended for site visitors. They are usually created by site
administrators.
Administration
Links to administrative tasks. This menu mainly contains links supplied by modules
on your site.
User account menu
Links to tasks associated with the user account such as My account and Log out.
Footer
Links to important pages within the site intended for the footer. They are usually
created by site administrators.
Tools
Links to tasks necessary for site visitors. Some modules feature their links here.
You can customize menus in the following ways, using the menu administration
functionality:
 Creating new custom menus.
 Adding new menu links.
 Reordering menu links by setting their "weight" or by dragging them into
place.
 Renaming menu links.
 Changing the link title (the tooltip that appears when you mouse over a menu
link).
 Moving a menu link into a different menu by editing its Parent link property.
A menu link will only be shown to a visitor if they have the rights to view the page it
links to. For example, the admin menu link is not shown to visitors who are not
logged in.
3.2 Managing Taxonomy
What is Taxonomy?
Taxonomy is used to classify website content. One common example of taxonomy is
the tags used to classify or categorize posts in a blog website; the farmers market
website could use an ingredients taxonomy to classify recipes. Individual taxonomy
items are known as terms (the blog tags or recipe ingredients in these examples); and
a set of terms is known as a vocabulary (the set of all blog post tags, or the set of all
recipe ingredients in these examples). Technically, taxonomy terms are an entity type
and the entity subtypes are the vocabularies. Like other entities, taxonomy terms can
have fields attached; for instance, you could set up an image field to contain an icon
for each term. An individual vocabulary can organize its terms in a hierarchy, or it
could be flat. For example, blog tags normally have a flat structure, while a recipe
ingredients vocabulary could be hierarchical (for example, tomatoes could be a sub-
term of vegetables, and under tomatoes, you could have green and red tomatoes).
Taxonomy terms are normally attached as reference fields to other content entities,
which is how you can use them to classify content. When you set up a taxonomy
reference field, you can let users enter terms in two ways:
Free tagging
 New terms can be created right on the content editing form.
Fixed list of terms
 The list of terms is curated and managed outside the content editing form, and
users can only choose from the existing list when editing content.
Setting up Taxonomy
Goal
Create an Ingredients vocabulary and add it to the Recipe content type as a field that
can contain an unlimited number of values and that allows adding new terms to the
vocabulary.
Steps
In the Manage administrative menu, navigate to Structure > Taxonomy
(admin/structure/taxonomy).
You will see the Tags vocabulary that was created with the core Standard installation
profile.
Click Add vocabulary, and fill in the values below.

Click Save. You will be taken to the Ingredients page, which shows a list of all the
terms in this vocabulary.
Click Add term. Enter "Butter" in the Name field. Click Save.
You will receive a confirmation about the term you created. Add more terms. For
example, "Eggs" and "Milk".
In the Manage administrative menu, navigate to Structure > Content Types
(admin/structure/types). Click Manage fields for your Recipe content type.
Click Add field, and enter values from the table below. Click Save and continue.
On the following configuration screen, enter the values from the table below. Click
Save field settings.

On the following configuration screen, enter the values from the table below. Click
Save settings.
Click ‘Save settings’. You will be taken back to the Manage Fields page. A message
will be displayed saying that the configuration for Ingredients is complete.
4 Managing Media
4.1 Image Styles
What are image styles?
Image styles allow you to upload a single image but display it in several ways; each
display variation, or image style, is the result of applying one or more effects to the
original image. As an example, you might upload a high-resolution image with a 4:3
aspect ratio, and display it scaled down, square cropped, or black-and-white (or any
combination of these effects). The core software provides a way to do this efficiently:
Configure an image style with the desired effects on the Image styles page
(admin/config/media/image-styles).
The effects will be applied the first time a particular image is requested in that style.
The resulting image is saved.
The next time that same style is requested, the saved image is retrieved without the
need to recalculate the effects. The core software provides several effects that you can
use to define styles; others may be provided by contributed modules. Visit the Image
styles page via the Manage administrative menu, navigate to Configuration >
Media > Image styles (admin/config/media/image-styles) to see the image styles that
are defined by default.
Setting Up an Image Style

Goal
Add an image style and use it to display images on Vendor pages.
Steps
In the Manage administrative menu, navigate to Configuration > Media > Image
styles (admin/config/media/image-styles).
Click Add image style.
Enter the name Extra medium (300x200)
Click Create new style. The page Edit style Extra medium (300x200) appears.
In the Effect table, select Scale and crop. Click Add.
Fill in the fields as shown below.

Click Add effect. The image style is saved with the chosen effects.

In the Manage administrative menu, navigate to Structure > Content types


(admin/structure/types).
Click Manage display in the Operations dropdown for the Vendor content type. The
Managedisplay page (admin/structure/types/manage/vendor/display) appears.
Ensure that the secondary tab Default is selected.
Click the cogwheel next to Main image for the configuration options.
Fill in the fields as shown below.

Click Update.
Click Save. The new image style will be used while displaying Vendor content.

4.2 Working with Layout


Views
A view is a listing of content on a website. The core Views module handles the
display of views, and the core Views UI module allows you to create and edit them in
the administrative interface. When you define views, you are interested in taking data
from your website and displaying it to the user.

What types of data can be displayed using views?

You can create views to output practically any content entity that is stored in the
system.

What are the ways data can be output using views?


A listing created by a view can be in any of the following forms:
 Table with sortable fields
 Grid layouts
 Teasers or pictures that link to articles
 Blocks
 JSON output
 RSS feeds
 Calendars
 On-screen slideshows
Creating a content list view
Goal
Create a page listing vendors that will be automatically updated whenever a vendor is
added, deleted, or updated on the site.

Steps
In the Manage administrative menu, navigate to Structure > Views > Add view
(admin/structure/views/add). The Add view wizard appears.
Fill in the fields as shown below.
Click Save and edit. The view configuration page appears.
Click Add from the dropdown button in the Fields section. The Add fields pop-up
appears.
Enter the word "image" in the search field.
Check Main image in the table.
Click Apply. The Configure field: Content: Main Image pop-up appears.
Fill in the fields as shown below.

Click Apply. The view configuration page appears.


Click Add from the dropdown button in the Fields section. The Add fields pop-up
appears.
Enter the word "body" in the search field.
Select Body in the table.
Click Apply. The Configure field: Content: Body pop-up appears.
Fill in the fields as shown below.

Click Apply. The view configuration page appears.


Click Content: Title (Title) in the Fields list. The Configure field: Content: Title pop-
up appears.
Uncheck Create a label. This will remove the label that was created by the wizard.
Click Apply. The view configuration page appears.
Click Rearrange from the dropdown button in the Fields section. The Rearrange
fields popup appears.
Drag the fields into the right order: Image, Title. Body.
Click Apply. The view configuration page appears.
Optionally, click Update preview for a preview.
Click Save.

Navigate to the homepage and click Vendors from the main navigation to see the
result.

4.3 Blocks

Blocks are boxes of content rendered into an area, or region, of a web page (such as
"User Login" or "Who's online") that can be displayed in regions (such as footer or
sidebar) on your page. This functionality is provided by the Block module, which is a
part of Drupal 8 core. Drupal 8 also introduces another module apart from Block that
allows the creation of custom blocks through the user interface and it is "Custom
Block" module. There was an experimental module which was also introduced in core
(Place Blocks) which when enabled allowed administrators to place blocks from any
Drupal page, but it was superseded by Layout Builder non-reusable
blocks functionality in Drupal 8.7. 

Blocks are made available to your site most commonly by enabling core or
contributed modules. Once created, a Block can be modified to adjust its appearance,
shape, size and position - or which Website pages it appears on. Any custom or
contributed block can be assigned to a particular region by clicking on a button Place
block. If block is already enabled, its region can be changed by choosing specified
regions from drop-down. For example, to assign any block in Header region, click on
"Place Block" button and choose any block to be placed in this particular region.

An Image showing Place block button and a list of regions for changing block
position.
You can place one block at multiple regions. Here I'm placing Page title (Core block)
in Header region. Click Place block button for Page title block and you will see a
configuration popup showing:
Hitting Save block button will place Page title block inside Header region.
Blocks are placed in regions via the Block Admin page Administer > Structure >
Block Layout.
Your site's theme defines the regions available. Therefore, block placement in regions
is done per theme on the Block Admin page. If you have more than one theme
enabled on your site blocks can be placed differently for each theme.

5 Working with Advanced Content


5.1 Working with Forms and Fields

5.2 Creating New Content Types

Nodes
All content on a Drupal website is stored and treated as "nodes". A node is any piece
of individual content, such as a page, poll, article, forum topic, or a blog entry.
Comments are not stored as nodes but are always connected to one. Treating all
content as nodes allows the flexibility to create new types of content. It also allows
you to painlessly apply new features or changes to all content of one type.
Entity Types
In earlier versions of Drupal, the field system was only used on content types. Now,
thanks to the Entity API, we can add fields to other things, like comments.
Fieldable entities make Drupal eminently flexible. An entity type is a useful
abstraction to group together fields. Below are the Entity types in Drupal core:
 Nodes (content)
 Comments
 Files
 Taxonomy terms
 Taxonomy vocabularies
 Users

You can also build new kinds of entity types where the options above don't suit your
needs

Fields
A field is a reusable piece of content. In technical terms, each field is a primitive data
type, with custom validators and widgets for editing and formatters for display
Follow the steps below to create custom content type.
Step 1 – Click on Structure and then on Content types as shown in the figure below.

Step 2 – You will see the following screen. Click on Add Content type to create new
content type.
Step 3 – Fill details of content type and click on Save and manage fields

Below are the fields present in custom content type.


Name: Name of the content type
Description: Explain the use of the content type
Title: Label of the Title field that is shown when editing or creating content of this
type
Preview before submitting: Option to choose whether you should preview the content
before submitting.
Explanation or submission guidelines: Instructions for creating or editing content.

Step 4: The new content contains body field by default. Click Add field to add new
fields in addition to body.
Step 5: Click on select a field type and choose Text (plain) from Text group.

Step 5: The following screen will appear. Enter the field name on label and click Save
and continue. It will automatically go to the field settings tab. Accept the default
values and finish by clicking Save fields settings and the on Save settings.

Step 6: Finally you will see that a new field is added. You can also manage forms and
displays on the next tabs as needed. But now we will accept the defaults and go to the
next step to use the new content type.
Step 7: Click on Content and then on Add content as usual.

Step 7: Now the custom content type ‘Vehicle’ in this example is added in the content
type lists.
Step 8: Click on the new content type and you will see the new field in the form. Fill
the details and save to see your new content type in your page.

5.3 Adding Interaction with Queries


6 System and Site Configuration
6.1 System Settings and Configuration
This administrative account is automatically given all privileges for managing
content and administering the site. Administrators will generally need to address the
following areas in a new site.
6.1.1 Reports

Available Updates
Check here if module updates are available. If so you have to update that module to
its latest version

Recent Log Messages


Any warning or error messages of the system will be listed here.

Status Report
Open the Status report via Menu > Reports > Status report (admin/reports/status) to
get an overview of your site's current status. You can check the Drupal version,
database version, PHP version, PHP memory limit, web server information, and
potential security issues. Items with a red background are issues that need immediate
attention. An example would be a required security update for Drupal core or an
installed module, or an unprotected settings.php file.
6.1.2 People

Open the People page via Menu > People (admin/people) to add new users or manage


existing users. You can manage user roles and permissions by clicking on the
"Permissions" tab on this page. To change the process by which users apply for
accounts, visit the "People and Permissions" page via Menu > Configuration >
People > Account settings (admin/config/people/accounts)

6.1.3 Structure

Open the Structure page via Menu > Structure (admin/structure) to manage blocks


layouts, content types, menus, taxonomies, views and others. Click on Block layouts
and you will see a screen that looks like the following figure.
Click on Place block to place any custom or installed block on the given region. You
can also click on configure and manage the pages, content types and roles of this
block.

6.1.4 Configuration

System
o Basic Site Settings: To change site name, email, slogan, default front pages
and error pages.
o Cron: To manage automatic site maintenance tasks.
People
o Account Settings: To configure default user account settings, including fields,
registration requirements, and email messages.
Content Authoring
o Text formats and editors: To select and configure text editors, and how
content is filtered when displayed.
User Interface
o Shortcuts: To add and modify shortcut sets.

Development
o Performance: To configure caching and bandwidth optimization. You can
clear caches here.
o Logging and Errors: To configure the display of error messages and database
logging.
o Maintenance Mode: To take the site offline for updates and other
maintenance tasks.
o Configuration Synchronization: To import and export your configuration.
Media
o File System: To configure the location of uploaded files and how they are
accessed.
o Image Styles: To configure styles that can be used for resizing or adjusting
images on display.
Regional and language
o Date and time formats: To configure the locale and time zone settings.
o Languages: To configure languages for content, interface, and configuration.
Web services
o RSS Publishing: To configure the site description, the number of items per
feed, and whether feeds should be titles/teasers/full-text.

6.2 Working with the User Interface


6.3 Managing Media
It is possible to upload Medias such us images, documents, audios, videos and remote
video links and use it on adding contents.
Step 1: Go to admin > extend and install Media and Media Library modules.

Step 2: Click on Content > Media as shown in the figure below.


Step 3: Click on Add media > Image and upload image.
Now follow the following steps to use this media (image).
Step 1: Go to admin>Configuration>Text formats and editors.
Step 2: Configure the Full HTML text format. And you will the following screen.

Step 3: Drag the media icon from available buttons to active toolbars.
Step 4: Go to Content > Add Content > Article as shown below and you will find
media library icon is available. Click over it and add the image you uploaded earlier.
Note: if the icon is not found change the text format to FULL HTML.
6.4 Indexing, Metadata and Locale Configuration

7 User and Access Control


7.1 Users and Roles
There are three elements used for granting permissions:
o User
o Role
o Permission

When installing Drupal, you create a root administrator account in the system
(identifier 1 in the database). It can be compared to the root user in UNIX systems.
This user has access to all subpages and settings in the system.
You can add more users to the system. These could be, e.g. the editors responsible for
creating the content, or the moderators deciding whether to post the added comments.
If you want to assign permission to a given user, you do it indirectly by assigning a
role to them. There is no association between a user and permissions in Drupal. There
is a user-role association and a role-permission association.
There are three system default roles in Drupal:

Anonymous: Visitors to your site who are not logged into your site.

Authenticated: Anyone who has an account on your site and logs in is authenticated.
The Authenticated role also serves as the minimum set of permissions that is given to
all logged in users. Drupal sets some default permissions but you can change them.

Administrator: Users assigned the administrator role can do everything on the site.

The first of these roles is responsible for all non-logged-in users. For example: if you
want to add the ability to view user profiles for all non-logged-in for the "View user
information" permission, tick the checkbox in the "Anonymous User" column.

"Authenticated User" is the role assigned to all logged-in users. It is important here to
understand the permission inheritance. If you assign permission to "Authenticated
User", then all other roles (except anonymous) will be given this permission
immediately.

Example: You have the "Editor" role in the system. You assign the "View user
information" permission to the "Authenticated User" role. Everyone with the "Editor"
role will also be given the permission because they are also considered to be logged-in
users. Moreover, keep in mind that if you select any permission for the Anonymous
role (e.g. "View user information" again), but do not select it for the "Authenticated
User", the logged-in users will not be able to access the selected section ("View user
information" – they will not have access to user profiles).
7.2 User Permissions

Permission enables users to have different privileges on the system. It is permission


that defines and limits user activities in the system.

Example

Goal

Creating an article writer

Start with the example of an Article writer. Such a person will be a role to which you
can assign users. If users are in this role, all they can do is write articles. There are
four steps to make sure a user account is set up correctly:

1. Add a role.

2. Set the role permissions.

3. Create a user.

4. Test the user to make sure it has the correct permissions.

Following are those four steps.

 Click on People on the admin menu bar and then on the Roles tab.
 Click "Add role".

 Type Article writer for the new role name.

 Click "Save"

Now that the Article writer role has been created, you need to decide what user in that
role can and can’t do.

 Click the Permissions tab to see the permissions available:

The permissions for the three default roles are already set. You can also see that some
permission for the Article writer role is already set. This is because those permissions
have been giving to the Authenticated User role. By default, if you grant permission
to the Authenticated role, all subsequent roles (except for anonymous) inherit said
permission. That is why the check marks for comments are grayed out and can't be
deselected.

Your article writer is going to need more permissions than those granted by default to
the Authenticated role, so let's get started.

 Scroll down until you find the header Node. Remember that Node is Drupal’s
geeky word for content.

 At the top of the Node area, you see some admin-type permissions, as shown
below:

Scroll a little further to find the Article permission set. To keep things simple in this
example, check all of the Article permission boxes:

 Create new content


 Delete any content
 Delete own content
 Delete revisions
 Edit any content
 Edit own content
 Revert revisions
 View revisions

 To ensure the Article writer can "Add Content", check the permissions box for
"Use the administration toolbar".

 Click "Save permissions" at the bottom of the page.


Now let's set up an actual user account for an Article writer.

 Click the "List" tab at the top of the screen.


 Click the "Add user" button.
As you can see by the absence of the red asterisk, an email address is not required.
However, the email is necessary for the user to receive messages, such as
password reset. If you have an email address, other than the one you used when
creating your first account, enter it now, so that you can see the emails users will
receive. Otherwise, leave it blank.
 Username: articlewriter
 Password: articlewriter
 Roles: Check the "Article writer" box.
 If you included an email address, check the box to "Notify user of new
account".
 Click "Create new account".
The fourth and final step is crucial. Permissions are a vital part of your site’s security,
and if you don’t test your permissions, you could easily allow some users to do things
that can compromise your site.
Following is a basic method for testing. You can use the following steps:
 Open a browser where you are not already logged in.
 Log in by going to http://[your_web_address]/user/login.
 Observe that the menu bar to which you have grown accustomed is lacking in
options. That is good. First test passed.

8 Drupal Modules
A Drupal module is a collection of files containing some functionality and is written
in PHP. Because the module code executes within the context of the site, it can use all
the functions and access all variables and structures of Drupal core. In fact, a module
is no different from a regular PHP file that can be independently created and tested
and then used to drive multiple functionalities.
You can turn the features and functionality on by installing the module, and you can
turn it off by uninstalling the module; before uninstalling, you may need to remove
data and configuration related to the feature or functionality. Each module that is
installed adds to the time needed to generate pages on your site, so it is a good idea to
uninstall modules that are not needed.
The core download provides modules for functionality such as:
Managing user accounts (the core User module)
Managing basic content (the core Node module) and fields (the core Field and Field
UI modules; there are also core modules providing field types)
Managing navigation menus (the core Menu UI module)
Making lists, grids, and blocks from existing content (the core Views and Views UI
modules)
You can download additional contributed modules from
https://www.drupal.org/project/project_module, or create your own custom modules.

8.1 Finding Modules


Goal
Find and evaluate modules on Drupal.org
Steps
Go to Drupal.org, and navigate to Download & Extend > Modules
(https://www.drupal.org/project/project_module).
Filter for Admin Toolbar using the categories on the module search page. Fill in the
fields as shown below. And click Search.
Click on Admin Toolbar link and scroll down to see the project information as shown
below. Check the number of sites using this module and the version as well
Requires Drupal: ^8.8.0 || ^9: means that this module fits with Drupal version of 8.8
and above or 9.
Click the latest (upper) tar.gz or zip file to download the module.
Unzip this file in your project directory modules/contrib/ folder.
Go to your site and click on Extend and search for Admin Toolbar as shown in the
figure below.

Check your module (admin toolbar), scroll down and click on Install.
Now hover on admin toolbar links to see the result.
Optionally you can install modules using drush.
After placing downloaded files in the project modules/contrib folder you can use the
following command to install the module.
* drush en admin_toolbar.
* drush pm-uninstall admin-toolbar to uninstall the module.

9 Drupal Themes
A theme is a set of files that define the visual look and feel of your site. The core
software and modules that run on your site determine which content (including
HTML text and other data stored in the database, uploaded images, and any other
asset files) is displayed on the pages of your site. The theme determines the HTML
markup and CSS styling that wraps the content. The core software provides several
basic themes with the core distribution. These themes have largely been designed and
built by the community over the last several years and will all be good choices for
building your first sites and becoming more familiar with how the core software
works. Drupal is a well-established CMS so the market for 3rd party themes - both
free and paid – is very robust. If none of the 3rd party options suit your needs, you’ll
need to create a custom theme. A custom theme can be as simple as a single CSS file
that adds styling to the markup provided by the core software. Guidance for creating
custom themes in Drupal 8 can be found in the Drupal.org community documentation
page "Theming Drupal".

9.1 Distributions
Distributions provide site features and functions for a specific type of site as a single
download containing the core software, contributed modules, themes, and pre-defined
configuration. A distribution makes it possible to set up a complex, use-specific site in
fewer steps than installing and configuring elements individually.
There are two main types of distributions:
Full-featured Distributions: A full-featured distribution is a project that provides a
complete solution to set up a site for a specialized purpose such as academic,
business, government, nonprofit, publishing, social, etc. For example, you could use
an existing distribution for farmers markets to build your own website, or you could
share your set-up for the farmer’s market site as a distribution for others to use.
Other Distributions: Distributions can also be quick-start tools that developers and
site builders can use as a starting point.
Working with the Admin in Themes
9.2 Configuring the Theme

Goal
Edit the settings of the default core Bartik theme to change the color scheme and to
add a logo.
Steps
In the Manage administrative menu, navigate to Appearance (admin/appearance).
Under Installed Themes, you will find Bartik listed as your default theme. Under
Bartik (defaulttheme), click Settings.

Under Color scheme, click inside each color build box and type the proper color
codes you would like to add. You can also use the color wheel on the right to select
colors of your choice. The web color codes will be added for you.

Under Logo Image Settings, uncheck Use the default logo supplied by the theme.
Under Upload logo image, locate a logo file and upload it to your site. Note: You can
also set a universal logo for all themes under Appearance > Settings
(admin/appearance/settings). A custom logo for your theme will override the
universal logo. Once you have selected the file you would like to upload, you will see
its filename next to the Choose File button.
In order to save your changes and see the updated colors and logo on your site, click
Save configuration at the bottom of the page.

Note: Under Color scheme, there is a Preview section that displays a sample of how
your website will look with the new settings.

Click Return to site in the toolbar to verify that you have updated the core Bartik
theme settings for your website.

9.3 Regions in a Theme


Besides its primary content, a web page contains other content such as site branding
(site name, slogan, and logo), navigation aids (menus, links, and icons), formatted
text, and images. Each theme provides a set of named regions, such as Header,
Content, and Sidebar, where site builders may choose to place their content. The
available regions depend on the theme design. Only the Content region, which
contains the primary content, is required; others are optional. The core Bartik theme
provides the eighteen regions highlighted in the following image.
Finding and Installing Themes
Go to https://www.drupal.org/project/project_theme and download a theme of your
interest. And apply to your site.

Steps
Download the zip file
Unzip the file in drupalprojectdir/themes/contrib folder.
Go to Appearance > Add new theme, as shown below.
Click on Choose file and select the extracted folder.
Click Continue to finish installation.
Manage regions as needed.

9.4 Working with Custom Themes


Drupal 8 provides Bartik as the frontend theme for Drupal, but if you need a Drupal
custom theme then you can create your own Drupal theme development, thus
improving your Drupal theming skills. Custom theme development is explained in
detail in chapter 11.

10 PHP OOP
10.1 What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform
operations on the data, while object-oriented programming is about creating objects
that contain both data and functions.
 Object-oriented programming has several advantages over procedural
programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and
shorter development time
10.2 What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:

A class is a template for objects, and an object is an instance of class.


In php a class is defined by using the class keyword, followed by the name of the
class and a pair of curly braces ({}). All its properties and methods go inside the
braces:

Classes are nothing without objects! We can create multiple objects from a class.
Each object has all the properties and methods defined in the class, but they will have
different property values.
Objects of a class are created using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:

PHP built-in functions


PHP has over 1000 built-in functions that can be called directly, from within a script,
to perform a specific task.
PHP user defined functions
Besides the built-in PHP functions, it is possible to create your own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
A user-defined function declaration starts with the word function:
It’s very easy to create your own PHP function. Look at the following method /
function.
<?php
function welcome() {
echo "Welcome to PHP";
}

welcome();
?>

PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your
function. Following example takes two integer parameters and adds them together and
then prints them

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

10.3 Passing Arguments by Reference


It is possible to pass arguments to functions by reference. This means that a reference
to the variable is manipulated by the function rather than a copy of the variable's
value.
Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the
variable name in either the function call or the function definition.
<?php

function addFive($num) {
$num += 5;

function addSix(&$num) {
$num += 6;
}
$orignum = 10;

addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

This will display following result –


Original Value is 10
Original Value is 16
10.4 Annotation
Annotation is a form of syntactic metadata that can be added to source code.
Annotations can be embedded in and read using reflection mechanism. Annotations
can be placed in classes, methods, properties and functions.

use MVC\Route;

class FooController {
/**
*@Route("/api/foo", ["POST"], "foo_create")
*/
public function create(Request $request): Response
{
// specific implementation
}
}

class Foo
{
/**
* @var integer
*/
public $bar;
}

When you see @var integer in the source code, immediately preceding


the public $bar declaration, this little piece of meta-data tells us that the $bar property
is expected to contain a value of type integer. Now imagine you had to build an
HTML form that allows someone to edit a Foo object. When this information comes
back from a form-post, you will need to validate that the input is in fact an integer -
using the information from the @var annotation, you could abstract and automate this
process, rather than having to code in by hand every time
11 Twig
Twig is flexible, fast, and secure template engine for PHP. Twig is both designer and
developer friendly by sticking to PHP's principles and adding functionality useful for
templating environments.
The key-features are...
Fast: Twig compiles templates down to plain optimized PHP code. The overhead
compared to regular PHP code was reduced to the very minimum.
Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows
Twig to be used as a template language for applications where users may modify the
template design.
Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to
define their own custom tags and filters, and to create their own DSL.
Symfony, Drupal8, Laravel, Codeigniter and others use Twig.
You can use composer require "twig/twig:^2.0" to install twig. In Drupal 8 it will be
installed by default during Drupal installation.
The following twig template is simply a text file. It can generate any text-based
format (HTML, XML, CSV, LaTeX, etc.). It doesn’t have a specific
extension, .html or .xml are just fine. A template contains variables or expressions,
which get replaced with values when the template is evaluated, and tags, which
control the logic of the template.

<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>

<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>

There are two kinds of delimiters: {% ... %} and {{ ... }}. The first one is used to


execute statements such as for-loops, the latter prints the result of an expression to the
template.

11.1 Variables
The application passes variables to the templates for manipulation in the template.
Variables may have attributes or elements you can access, too. The visual
representation of a variable depends heavily on the application providing it.

You can use a dot ( . ) to access attributes of a variable (methods or properties of a


PHP object, or items of a PHP array), or the so-called “subscript” syntax ( [] ):

{{ foo.bar }}
{{ foo['bar'] }}
You can assign values to variables inside code blocks. Assignments use the set tag:
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}

11.2 Comments
To comment-out part of a line in a template, use the comment syntax  {# ... #} . This
is useful for debugging or to add information for other template designers or yourself:
{# note: disabled template because we no longer use this
{% for user in users %}
...
{% endfor %}
#}

Control structure
A control structure refers to all those things that control the flow of a program -
conditionals (i.e.  if / elseif / else ),  for -loops, as well as things like blocks. Control
structures appear inside  {% ... %}  blocks.

For example, to display a list of users provided in a variable called  users , use
the for tag:
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>

The if tag can be used to test an expression:


{% if users|length > 0 %}
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}

11.3 Filters
Variables can be modified by filters. Filters are separated from the variable by a pipe
symbol ( | ) and may have optional arguments in parentheses. Multiple filters can be
chained. The output of one filter is applied to the next.
The capitalize filter capitalizes a value. The first character will be uppercase, all
others lowercase:
{{ 'my first car'|capitalize }}

{# outputs 'My first car' #}

The join filter returns a string which is the concatenation of the items of a sequence:

{{ [1, 2, 3]|join }}
{# returns 123 #}

The separator between elements is an empty string per default, but you can define it
with the optional first parameter:
{{ [1, 2, 3]|join('|') }}
{# outputs 1|2|3 #}

The filter filter filters elements of a sequence or a mapping using an arrow function.


The arrow function receives the value of the sequence or mapping:
{% set sizes = [34, 36, 38, 40, 42] %}
{% for v in sizes|filter(v => v > 38) %}
{{ v }}
{% endfor %}
{# output 40 42 #}
Please go to twig documentation and see available filter functions.
(https://twig.symfony.com/doc/3.x/filters/index.html).

12 Composer
12.1 Package installation
Update and Upgrades
removing package
Composer is a tool for dependency management in PHP. It allows you to declare the
libraries your project depends on and it will manage (install/update) them for you.
Composer requires PHP 5.3.2+ to run.
Installation - Linux / Unix / macOS

php -r "copy('https://getcomposer.org/installer', 'composer-


setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') ===
'756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9
a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified';
} else { echo 'Installer corrupt'; unlink('composer-setup.php');
} echo PHP_EOL;"
php composer-setup.php

php -r "unlink('composer-setup.php');" sudo mv


composer.phar /usr/local/bin/composer

12.2 Installation - Windows


Download and run Composer-Setup.exe. It will install the latest Composer version
and set up your PATH so that you can call composer from any directory in your
command line.

13 Custom Theme Development

13.1 Getting Started with Custom Drupal 8 Theme Development


Let’s get started with creating a Drupal 8 theme for our Drupal website.
STEP 1: First, we need to create a custom theme under ‘web/themes/custom’ folder.
We will name the folder as custom_theme.  
      Drupal Theming:  Create Custom Drupal 8 Theme folder
STEP 2: Next, we will need to create an info.yml file. We need to specify the basic
keys for it. Let us specify it over here –

     Drupal Theming: Create an info.yml file


CODE:
name: Custom Theme
type: theme
description: 'Custom Theme for My Website.'
package: Other
core: 8.x

STEP 3: Now, let’s create a libraries.yml file to specify all the libraries we need


(CSS AND JS) for our custom Drupal 8 theme. We will also create CSS and JS
directory and its files to link it in here. We are going to name the library as global-
styling.
       Drupal Theming: Create a libraries.yml file

CODE:
global-styling:
version: 1.x
js:
js/script.js: {}
css:
theme:
css/style.css: {}

STEP 4: After creating the libraries.yml file, we need to link it to our theme. For


this, we are going to add it in the info.yml file which will then apply it to the whole
theme. 

        Linking the libraries.yml with the custom Drupal 8 theme


CODE:
libraries:
- custom_theme/global-styling

So, the key will be libraries and path will be the theme name - ‘custom_theme’ /
library name - ‘global-styling’.
STEP 5: Next, we need to inherit the ‘Base Theme’.In our case, we will inherit the
‘classy’ theme which is a Drupal core theme. So, the key will be the base theme
in info.yml. 

        Inheriting the Base theme – classy


CODE:
base theme: classy

STEP 6: Now, we will define the ‘regions’ for our theme. In info.yml, we have to
define it under the ‘regions’ key.

          Defining 'regions'


CODE:
regions:
branding: Branding
navigation: Main navigation
search: Search
featured: Featured
content: Content
right_sidebar: Right sidebar
footer_first: Footer First
footer_second: Footer Second
footer_third: Footer Third
footer_bottom: Footer Bottom
Under ‘regions’ key, you can define your regions for the custom Drupal theme. Here,
branding: Is the id of the region which should be lowercase letters. Branding: Is the
name of the region which can be uppercase letters.
STEP 7: After we have defined our regions for our custom Drupal theme, we need to
override page.html.twig to grab our ‘regions ‘instead of the classy theme’s. We will
create templates/system directory under which we will create the page.html.twig.

       Override the page.html.twig


CODE:
<header aria-label="Site header" class="header" id="header" role="banner">
{{ page.branding }}
{{ page.navigation }}
{{ page.search }}
</header>
<section class="featured" id="featured" role="complementary">
{{ page.featured }}
</section>
<section class="main" id="main">
<main aria-label="Site main content" class="content" id="content" role="main">
{{ page.content }}
</main>
<aside class="right--sidebar" id="sidebar" role="complementary">
{{ page.right_sidebar }}
</aside>
</section>
<footer aria-label="Site footer" class="footer" id="footer" role="contentinfo">
<div class="footer--top">
{{ page.footer_first }}
{{ page.footer_second }}
{{ page.footer_third }}
</div>
<div class="footer--bottom">
{{ page.footer_bottom }}
</div>
</footer>

 In page.html.twig, we will create the HTML structure for our regions. As you see in
{{ page.branding }} – Here,
page - Is the key to render ‘regions’ in the page
branding- Is the region which we have defined in info.yml file. So now, we have
created our regions and rendered it on the page.
Step 8: Go to Appearance in your Drupal site. You can see your custom Drupal theme
present in the Uninstalled themes section.

       Regions added in info.yml and page.html.twig


Step 9: You are now almost done with theming in Drupal 8! Next, you need to apply
styles in the CSS for each region as per your design. We will use CSS in this case;
You can even use SCSS if you’d like. Just inspect the branding region - you should
see the region class and then add the CSS to that class.
Add CSS in style.css as per your requirement.
.header{
display: flex;
justify-content: space-between;
padding: 10px;
}
.header.region {
padding: 5px;
}
.header.region-branding {
flex: 0 1 20%;
}
.header.region-navigation {
flex: 0 1 50%;
}
.header.region-search {
flex: 0 1 30%;
}
.region.block-region {
padding: 15px;
}
.featured{
padding: 40px 20px;
background-color: indianred;
}
.main{
padding: 50px 0;
display: flex;
justify-content: space-between;
}
.main.content {
flex: 0 1 65%;
}
.main.right--sidebar {
flex: 0 1 30%;
}
.footer--top {
display: flex;
justify-content: space-between;
padding: 10px;
}
.footer--top .region {
padding: 5px;
}
.region-footer-first, .region-footer-second, .region-footer-third {
flex: 0 1 30%;
}

 The Result:
Your Drupal 8 Custom Theme is ready!
14 Custom Module Development

14.1 Getting started with Module development in Drupal 8


Let’s now get started with creating a custom module in Drupal 8 in a few easy steps:
Step 1: Name the Drupal 8 Module
First, we need to create a custom module under ‘web/modules/custom’ folder. We
will name the folder as portal.
Some things that you should keep in mind before giving a machine name to your
module are:
 It should not start with uppercase letters.
 There should not be any spaces between the words.
Step 2: Get noticed with 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.
Here is our portal.info.yml file created under "portal" directory we created in Step 1.
name: 'City Portal'
description: 'A module for city website'
package: Portal
type: module
version: 1.0
core: 8.x
core_version_requirement: ^8 || ^9

name: Portal Module (The name displayed on the modules list in Drupal) 
description: Custom Example Drupal 8 Module
package: Custom - (Mentioning that this is a custom module)
type: module - (Declaring that this is a module or theme)  
version: 1.0 - (Module version) 
core: 8.x - (Drupal version)
core_verstion_requirement: ^ 8 || ^9 - (Drupal version)

Step 3: Creating the routing file with routing.yml


Next step is to add a portal.routing.yml file under the "portal" directory:
portal.welcome:
path: '/welcome/page'
defaults:
_controller: '\Drupal\welcome_module\Controller\WelcomeController::welcome'
_title: 'Welcome to My Module in Drupal 8'
requirements:
_permission: 'access content'

The first line is the route name [portal.my_welcome].


Under path, we specify the URL path we want this route to register. This is the URL
to the route. Under defaults, we have two things: the _controller which references a
method on the WelcomeController class and the default page title (_title). Under
requirements, we specify the permission of the accessing. User needs to have to be
able to view the page.
Step 4: Adding a Controller 
Create a folder "modules/custom/portal/src/Controller". In this folder, create a file
named "WelcomeController.php" with the following content:
<?php

namespace Drupal\welcome_module\Controller;
class WelcomeController {
public function welcome() {
return array(
'#markup' => 'Welcome to our Website.'
);
}
}
Now Login to your Drupal site and enable your module. To check if it functions
properly, visit the path you specified in your routing file, that is /welcome/page. If
you get the ‘Page Not Found’ error, then clear the cache by navigating to admin-
>configuration->performance. Check again and it should function properly this time.
14.2 Forms
There are several types of forms commonly used in Drupal. Each has a base class
which you can extend in your own custom module.
First, identify the type of form you need to build:
1. A generic form. Extend FormBase.
2. A configuration form that enables administrators to update a module's settings.
Extend ConfigFormBase.
3. A form for deleting content or configuration which provides a confirmation
step. Extend ConfirmFormBase.
FormBase implements FormInterface, and both ConfigFormBase and
ConfirmFormBase extend FormBase, therefore any forms that extend these classes
must implement a few required methods.
Required Methods
FormBase implements FormInterface, and therefore any form that has FormBase in
its hierarchy is required to implement a few methods:
 getFormId()
 buildForm()
 submitForm()

getFormId()
public function getFormId()
This needs to return a string that is the unique ID of your form. Namespace the form
ID based on your module's name.
Example:
public function getFormId() {
return 'mymodule_settings';
}
buildForm()
public function buildForm(array $form, FormStateInterface $form_state)
This returns a Form API array that defines each of the elements your form is
composed of.
Example:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['phone_number'] = [
'#type' => 'tel',
'#title' => $this->t('Example phone'),
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
return $form;
}
14.3 Plugins
The Drupal plugin system allows a particular module or subsystem to provide
functionality in an extensible, object-oriented way. The controlling module defines
the basic framework (interface) for the functionality, and other modules can create
plugins (implementing the interface) with particular behaviors. Plugins are small
pieces of functionality that are swappable. Plugins that perform similar functionality
are of the same plugin type. Blocks are the classic example. In Drupal every block
consists of essentially the same parts: a label, some content, and various settings
related to visibility and cacheability.
Example of Plugins
Step 1: create a file named WelcomeBlock.php in portal/src/Plugin/Block directory
and add the following content.
<?php
namespace Drupal\portal\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a block called "welcome block".
*
* @Block(
* id = "welcome_block",
* admin_label = @Translation("welcome block")
* )
*/
class WelcomeBlock extends BlockBase
{
/**
* {@inheritdoc}
*/
public function build()
{

return [
'#type' => 'markup',
'#markup' => '<h2> Welcome to custom block plugin page! </h2>'
];
}
}
Step2: got to admin > structure > blocks and place the new block (welcome block)
and you will see the result.

You might also like