Professional Documents
Culture Documents
Drupal Training Manual
Drupal Training Manual
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.
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
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.
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.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.
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 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.
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
Extend
Configuration
People
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 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.
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.
Click Update.
Click Save. The new image style will be used while displaying Vendor content.
You can create views to output practically any content entity that is stored in the
system.
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.
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.
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
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.
Available Updates
Check here if module updates are available. If so you have to update that module to
its latest version
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
6.1.3 Structure
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.
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
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
Example
Goal
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.
3. Create a user.
Click on People on the admin menu bar and then on the Roles tab.
Click "Add role".
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.
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:
To ensure the Article writer can "Add Content", check the permissions box for
"Use the administration toolbar".
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.
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.
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.
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:
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:
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);
?>
function addFive($num) {
$num += 5;
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
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;
}
<!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>
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.
{{ 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>
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 }}
{{ [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 #}
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
CODE:
global-styling:
version: 1.x
js:
js/script.js: {}
css:
theme:
css/style.css: {}
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.
STEP 6: Now, we will define the ‘regions’ for our theme. In info.yml, we have to
define it under the ‘regions’ key.
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.
The Result:
Your Drupal 8 Custom Theme is ready!
14 Custom Module Development
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)
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.