Envato Tuts+: Using and Extending the Drupal 8 Mail API: Part 1

In this two part series we are going to explore the Mail API in Drupal 8. In doing so, we are going to cover two main aspects: how to use it programatically for sending emails and how to extend it for using an external service like Mandrill.

To demonstrate this, in the first part we will create a custom email template that gets used for sending emails to the current user when s/he saves a new Article node. Additionally, we will see how others can alter that template in order to allow for HTML rendering of the email body instead of the default plain text.

In the second part we are going to look at extending the mail system and integrating an external API for email delivery. For this, we will use Mandrill and its PHP library that provides a good foundation for interacting with its API.

All the work we go through can be found in this Git repository as part of a custom Drupal 8 module that we will start writing here. So feel free to check that out if you want to follow along. Let's get started.

The first prerequisite of this module is its .info file:

d8mail.info.yml:

1 name: Drupal 8 Mailer 2 description: 'Demonstrates the use of the Mail API in Drupal 8.' 3 core: 8.x 4 type: module

With this out of the way, we can already enable the module on our site if we want.

How Do We Send an Email?

There are two main steps needed to send an email programatically with Drupal 8. We first need to implement hook_mail() in order to define one or more email templates. The second step is to use the mail manager to send emails using one of these templates.

Although called a hook, hook_mail() is not a typical hook but more of a regular function that generally gets called only by the same module that implements it. In other words, when you send an email programatically, you need to specify the module name implementing hook_mail() and the template id you want to use and that is defined by this hook. But we'll see that in a minute. First, how do we implement it?

d8mail.module:

1 /** 2 * Implements hook_mail(). 3 */ 4 function d8mail_mail($key, &$message, $params) { 5 $options = array( 6 'langcode' => $message['langcode'], 7 ); 8 9 switch ($key) { 10 case 'node_insert': 11 $message['from'] = \Drupal::config('system.site')->get('mail'); 12 $message['subject'] = t('Node created: @title', array('@title' => $params['node_title']), $options); 13 $message['body'][] = SafeMarkup::checkPlain($params['message']); 14 break; 15 } 16 }

This is a very simple implementation that defines one template identified as node_insert (the $key). The other two function arguments are:

  • $message: passed by reference, and inside which we add as much boilerplate about our email as we need 
  • $params: an array of extra data that needs to go in the email and that is passed from the mail manager when we try to send the email

As you can see, we are building up the $message array with values we want this email to include in all the calls. We are setting a default from value that is retrieved from the configuration system and that represents the main site email address. We set a boilerplate email subject that lets the recipient know a new node was created, followed by the name of the node (which will be passed in through the $params array). The subject is also translatable into the language that gets passed from the caller. 

Lastly, we run the message body through the string sanitiser because the text may contain HTML and it might get truncated if we don't encode the HTML elements. And since we are using the SafeMarkup class, we need to use it at the top:

1 use Drupal\Component\Utility\SafeMarkup;

Additionally, the message body is an array that will later be imploded into a string. And obviously there are many other parameters we can set, such as headers, but this will suffice for this example.

And that's all for the hook_mail() implementation. Now let's turn to the code which gets run every time a new node is created, hook_entity_insert():

1 /** 2 * Implements hook_entity_insert(). 3 */ 4 function d8mail_entity_insert(Drupal\Core\Entity\EntityInterface $entity) { 5 6 if ($entity->getEntityTypeId() !== 'node' || ($entity->getEntityTypeId() === 'node' && $entity->bundle() !== 'article')) { 7 return; 8 } 9 10 $mailManager = \Drupal::service('plugin.manager.mail'); 11 12 $module = 'd8mail'; 13 $key = 'node_insert'; 14 $to = \Drupal::currentUser()->getEmail(); 15 $params['message'] = $entity->get('body')->value; 16 $params['node_title'] = $entity->label(); 17 $langcode = \Drupal::currentUser()->getPreferredLangcode(); 18 $send = true; 19 20 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send); 21 if ($result['result'] !== true) { 22 $message = t('There was a problem sending your email notification to @email for creating node @id.', array('@email' => $to, '@id' => $entity->id())); 23 drupal_set_message($message, 'error'); 24 \Drupal::logger('d8mail')->error($message); 25 return; 26 } 27 28 $message = t('An email notification has been sent to @email for creating node @id.', array('@email' => $to, '@id' => $entity->id())); 29 drupal_set_message($message); 30 \Drupal::logger('d8mail')->notice($message); 31 }

This hook gets triggered after every node save, and all we have to do is make sure we are targeting the correct node and include our logic.

After checking that the node entity is of the type article, we load the Drupal mail manager service and start setting some values for the email. We need the following information:

  • the module name that implements hook_mail() and defines our template (what I mentioned above)
  • the template id (the $key)
  • the recipient email address (the one found on the current user account)
  • the language ($langcode) which goes inside the $params array and which will be used to translate the subject message
  • the node title that will get added to the email subject
  • the email body, which in our case will be the value of the node's body field
  • the boolean value indicating whether the email should be actually sent

We then pass all these values to the mail() method of the mail manager. The latter is responsible for building the email (calling the right hook_mail() implementation being one aspect of this) and finally delegating the actual delivery to the responsible plugin. By default, this will be PHPMail, which uses the default mail() function that comes with PHP.

If the mail manager is successful in sending the email (actual delivery is not taken into account but rather a successful PHP action), the mail() method will return an array containing a result key with whatever the mail plugin returns. Checking for that value, we can learn whether the email action was successful and inform the user that we have notified them of their action. Otherwise, we print and log an error message.

And that's about it. Clearing the cache and creating an article node should land an email in your inbox. If you are not getting anything and there are no error signs on your screen, make sure you check your server logs and mail queue to verify that emails are being sent out.

Before moving on, I would like to make a quick note regarding this hook implementation. In this example, I placed all the logic inside it directly. Additionally, I used an early return at the top, which essentially means no other logic can be added but the one specific to the article nodes. In real applications I recommend refactoring the mailing logic into a separate function or class and deferring to that. Moreover, you should not use early returns inside hook implementations but instead call other functions if the conditions are met. 

How Do We Alter an Email?

Once all of this is in place, we have another tool at our disposal that allows us to alter such an existing setup: hook_mail_alter(). This hook is called from within the mail manager before the responsible mail plugin sends the email. The purpose is to allow other modules to perform final alterations to an existent email being sent out.

Although this can be used by other modules as well, we will illustrate an example implementation from within the same module we've been working with. To this end, we will alter the email by changing one of its default headers in order to transform it from plain text to HTML. And this is how we can do this:

1 /** 2 * Implements hook_mail_alter(). 3 */ 4 function d8mail_mail_alter(&$message) { 5 switch ($message['key']) { 6 case 'node_insert': 7 $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes'; 8 break; 9 } 10 }

As you can see, this is a simple alteration of the Content-Type header that transforms the email into HTML. This way plain text HTML entities will be parsed as HTML by mail clients. And using the switch case, we make sure this only happens for the email template we defined earlier.

One thing to note here is that the alter hook gets called after the relevant hook_mail() implementation. So after this, the only processing that happens on the email is done inside the format() method of the mail plugin (enforced by its interface).

Conclusion

And that is pretty much all there is to sending emails programatically using Drupal 8. We've seen the steps required to programatically set up email templates that get hydrated by the mail manager whenever we want it. We've also mentioned the default mail delivery plugin which is used to send emails in Drupal 8. And lastly, we've seen how other modules can now alter our email by adding new headers, changing the subject, concatenating values to the mail body, etc.

In the next article we are going to look at replacing the default PHPMail plugin with our own custom implementation. We will set up a mailer that uses Mandrill with the help of its PHP library. The goal is to allow our own module to use this mailer while the rest of the application continues to use the default PHPMailer.

Envato Tuts+: Create a Facebook Recent Activity Drupal Module

Image removed.Image removed.Image removed.

Enhancing Drupal's built-in functionality with new modules is one of the features that attracted a lot of developers to the platform and made it extremely popular. This tutorial will demonstrate how to create a Drupal module, using techniques recommended by Drupal gurus.

Before getting our hands dirty, let's take a look at what are we going to learn.

Prerequisites

In order to fully understand the information presented in this tutorial, you need to have the following knowledge:

  • basic Drupal administration including installing Drupal, enabling a module, adding some content
  • basic PHP knowledge

Drupal Hooks

The Drupal codebase is modular and consists of two parts:

  • the core modules (the core)
  • the contributed modules (the modules)

The core provides all the basic Drupal functionalities, and the modules add more features to the base installation. Interaction between modules and the core is done via "hooks".

According to Drupal's documentation:

"A hook is a PHP function that is named foo_bar(), where foo is the name of the module (whose filename is thus foo.module) and bar is the name of the hook."

So, the hook is a function with a special name that is called by the Drupal system in order to allow modules to include their functionality to the core. The file containing these functions also has a special name which allows the core to find all the installed modules.

The Drupal API provides the developer with a large number of hooks with which to alter almost the whole functionality of the core. For a Drupal developer, the sky is the limit for creating a site based on this powerful CMS.

Separating the basic functionality from the auxiliary features enables an increased flexibility on performing administrative tasks such as upgrading Drupal to a newer version. Since the core is somehow independent on modules, this operation can be done just by overriding the core.

What We're Building Today

We need a realistic goal for implementing our module, and I think Facebook integration is the perfect idea. We will allow the user to "like" our articles by adding a Facebook 'Like' button to each of them. The second task of our module will be to show, in the sidebar, which articles were liked by the users.

Obtaining the Data

Since the main focus of this article is on how to implement a Drupal module, we will use the simplest method to retrieve the data from Facebook: Social Plugins. Social Plugins allow users to add Facebook elements to your site with only a single line of code, which can be taken out with copy/paste from the Facebook site.

Our final product will have an output which should look like so:

Image removed.

Step 1: Setup

Drupal searches for contributed modules in the sites/all/modules folder of your Drupal installation. In case an administrator decides to have multiple sites driven by one Drupal installation, the path to the contributed module will look like sites/subdomain/modules.

First, let's choose a name for our module. Since its task will be to add Facebook functionality to our site, I assume "facebook" will be a proper name for it. We can start preparing the required directory structure for developing our module.

Inside sites/all create a subfolder, named modules. We will store our contributed modules in a subfolder named custom. The Facebook module will reside in the facebook subdirectory of the custom directory. The final structure will look like so:


Image removed.

Step 2: Inform Drupal about our Module

Drupal presents the user with a list of core and contributed modules based on the content of sites/all/modules. For each module present, Drupal searches for a file named module_name.info. This file should contain information about the specific module and Drupal displays this information to the user.

Let's create the info file for our module. Create a file, named facebook.info in the sites/all/modules/custom/facebook folder, and add the following code to it:

1 2 ; the module's user friendly name, will be displayed in the modules list 3 name = Facebook Recent Activity 4 ; the module's description, will be displayed in the second column in the modules list 5 description = Retrieves and displays in a block the recent activity data from Facebook. 6 ; the module's package, will be the name of the module's group on the modules list page 7 package = Nettuts+ Drupal Module Tutorial 8 ; the Drupal core package 9 core = 7.x 10 ; the files array indicating which files are part of the module 11 files[] = facebook.module

The code above reveals the required information to be placed in an info file. Notice that we've referenced the facebook.module in the files array. This file will contain our module's code. For the moment, go ahead and create an empty file in our folder.

The .info file is a standard .ini file; therefore, the lines starting with ";" are comments.

Checkpoint

Now, let's check what we've done so far. Visit your website and select Modules from the upper main menu. The modules list should be displayed, and at the bottom of it, you will find a new module group, named Nettuts+ Tutorial Module containing our module. Check out how the information you've placed in the info file is displayed here.

Image removed.Image removed.Image removed.

Step 3: Add the Like Button

We need to add the code provided by Facebook to the Drupal code that processes the node. This can be done by implementing hook_node_view.

As we will find in a moment, implementing hook_node_view requires using the theme function.

A theme function is a Drupal API function that is used to allow desginers to theme the modules as desired. The fact that we will use the function also means that we will have to implement hook_theme too.

Retrieving the Code from Facebook

The Facebook code that displays the 'Like' button on the pages can be obtained here. You can customize the look of the button using the controls on the page. Pressing the Get Code button displays the required XFBML code.

Image removed.Image removed.Image removed.

Implement hook_node_view

The hook_node_view returns the renderable view of the nodes (articles or pages for instance). Using this hook, we can add custom code to the one generated by Drupal by default. The implementation of this hook looks like so:

1 2 /** 3 * Implements hook_node_view(). 4 * 5 * Returns the renderable view of our nodes (pages or articles). 6 * We want to moddify the code so that we add the like button 7 * to our pages. 8 */ 9 function facebook_node_view($node, $view_mode, $langcode) 10 { 11 $node->content['facebook'] = array( 12 '#markup' => theme('facebook_add_like_button'), 13 ); 14 }

The name of the function is facebook_node_view, so you can deduce that it is composed from the name of our module and the name of the hook.

The parameters are:

  • $node -- contains the node data that will be rendered lately
  • $view_mode -- specifies how the node is displayed (can be full mode, teaser etc.)
  • $langcode -- to control the language code for rendering

We modify only the $node parameter and the result will be that our 'Like' button will appear also when a node teaser is displayed. I leave it as an exercise for you to modify the code to display the Like button only on full pages.

The code adds a new key to the $node->content array, which says that the markup for the facebook module will be rendered by the facebook_add_like_button function.

Implement hook_theme

This hook should be implemented to register the implementation of the theme function.

1 2 /** 3 * Implements hook_theme(). 4 * 5 * Just to let Drupal know about our theme function. 6 */ 7 function facebook_theme() 8 { 9 return array( 10 'facebook_add_like_button' => array('variables' => NULL), 11 ); 12 }

The code returns an array containing the name and parameteres of the function. In our case, we don't require any parameters, so the array of variables is set to NULL.

Implement our theme Function

Finally, we've reached the moment when we can add the code taken from Facebook to our module. This can be done like so:

1 2 /** 3 * Function to add the desired code to our page. 4 */ 5 function theme_facebook_add_like_button() 6 { 7 $output = '<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=221371084558907&xfbml=1"></script><fb:like href="http://www.facebook.com/profile.php?id=100000782572887" send="true" width="450" show_faces="true" font=""></fb:like>'; 8 9 return $output; 10 }

Note that the function's name is composed from the name registered by theme hook prefixed with theme_. The function returns a string containing the code taken from Facebook.

Checkpoint

We can now check to see if everything is okay up to this point. You can activate the module by clicking on Modules from the upper menu, scrolling down to the Facebook module and activating the enable check box in front of our module.

Click on Save configuration button to enable the module. If you do not have any articles added to your site, add some now and check out the spiffy buttons that have been added.

Your posts should look like below:

Image removed.Image removed.Image removed.

Step 4: Create the Sidebar Block

Creating the sidebar block consists of two actions:

First, we have to let Drupal know about the existence of a new block and make it appear in the list of available blocks. Second, we have to write the code that displays information in the block.

This assumes implementation of the hooks: the hook_block_info, which will list our block in the block list, and hook_block_view, which contains the necessary code to display the Facebook recent activity inside the block.

Implementing hook_block_info

1 2 /** 3 * Implements hook_block_info(). 4 * 5 * Using this hook we declare to Drupal that our module 6 * provides one block identified as facebook 7 */ 8 function facebook_block_info() 9 { 10 $blocks['facebook'] = array( 11 'info' => t('Facebook Recent Activity'), 12 // leave the other properties of the block default 13 ); 14 15 return $blocks; 16 }

The block_info hook tweaks the $blocks array by adding a new key, named info to it, which contains the text that will be available on the blocks page near our Facebook module.

Implementing hook_block_view

The first thing to do is take the Facebook code, available here. We need to configure the default options: set the width to 170 and the header to false (uncheck the Show header checkbox).

We need a 170px wide block, since this is the standard Drupal block width and we will set up our own text for the header -- therefore, we don't need Facebook's title.

Let's check the code for hook_block_view:

1 2 /** 3 * Implements hook_block_view(). 4 * 5 * Returns the renderable view of our block. It takes 6 * the configured values of facebook recent activity 7 * social plugin 8 */ 9 function facebook_block_view($delta = '') 10 { 11 switch($delta) { 12 case 'facebook' : 13 $block['subject'] = t('Facebook recent activity'); 14 $block['content'] = '<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:activity site="" width="170" height="500" header="false" font="" border_color="#fff" recommendations="false"></fb:activity>'; 15 } 16 17 return $block; 18 }

The block view hook receives a single parameter, which is an indication of which block is rendered. We check to see if the block belongs to our module and, if yes, we add two new items to the $block array:

  • a subject string, which will be the title of the block
  • a content string, which, in our case, is taken from Facebook.

We're almost ready. Enable the module, then navigate to Structure in the main menu, then choose Blocks and scroll down to the disabled list of blocks, and set our Facebook recent activity block to be displayed in the second sidebar (which will appear on right on the default theme).

Next, press the like button for some of the articles previously created. These will appear listed in the sidebar in our freshly created block.

That's it! We're done. The result should look like so:

Image removed.Image removed.Image removed.

Wrapping Up

I hope this tutorial convinced you that creating a Drupal module isn't really as hard as you might think. Of course, this tutorial only scratches the surface of what Drupal modules can accomplish. Nonetheless, this should be an excellent starting point!

Thank you so much for reading and let me know if you have any questions!

Envato Tuts+: What's New in Drupal 7

Drupal is one of the most popular content management systems (CMS) out there. To mark the new year, Drupal 7, the next major version of Drupal, is being released! In this article, I'll walk you through some of the most exciting new features.

New Themes

The old themes have been replaced with powerful, new ones.

If you've worked with Drupal 6, you may have noticed the default "Garland" theme looks a bit outdated by now. Furthermore, using Garland for site administration and content editing is, frankly, not very intuitive.

Drupal 7 changes all that! The old themes have been discarded and replaced with a powerful theme trio:

  • Bartik - The attractive new default theme your users will see
  • Seven - The new administrative theme. If you've worked with Drupal 6, you will love this new administrative theme (more about that in a following section).
  • Stark - A blank theme that helps theme developers (aka the themers) understand Drupal's default HTML and CSS

As always, these themes can be replaced by a theme you download and install from Drupal.org or by a custom theme of your own making!

Revamped Admin Interface

One of the most intrinsic functions of any CMS, be it Wordpress, Joomla, or Drupal, is to provide an easy way for end-users to update content. Drupal 6 has some very good administrative themes, such as Rubik, but Drupal 7 makes creating, updating, and editing content far simpler. Take a look at the following short video to get a feel for the new administrative interface:



A video demonstration of the Drupal 7 Administrative Interface

Improved Theming Layer

Meaningful HTML is not a strong suit of Drupal 6, but Drupal 7 delivers big-time.

Another important features of any CMS is the ability to take full control over the look and feel of the site you're building. Drupal 6 has a fantastic theming layer, but it does have a few quirks that are ironed out in Drupal 7. As a note, template files in Drupal end with the .tpl.php extension, which is often pronounced "tipple-fip" for brevity.

If you've worked with Drupal 6 themes, perhaps the biggest change you'll notice is the introduction of html.tpl.php, which is used to display the basic html structure of a single Drupal page, including DOCTYPE, head, html, and body. In Drupal 6, page.tpl.php used to include these elements, but is now used specifically to display the content of a single page. This change should free themers from declaring DOCTYPES, head, etc. in multiple files, thus making maintenance and changes simpler.

Unsemantic class names have been renamed. For example, the class block-blog-0 has been renamed block-blog-recent, and block-profile-0 has become block-profile-author-information. While this may seem minor, meaningful and semantic classnames can greatly speed up theme development and make debugging CSS issues clearer.

There's far too much to cover in one small section, from hidden regions to new PHP functions. If you're interested in learning more about changes to the theme layer, check out the following links:

jQuery Updates

For the front-end developers out there, this is a big one. Unfortunately, Drupal 6 still ships with jQuery 1.2.6, and upgrading isn't simple. Luckily, Drupal 7 ships with jQuery 1.4.4, which is significantly faster than jQuery 1.2.6, and provides developers with access to fantastic features such as .delegate() and $.proxy().

Drupal 7 ships with jQuery 1.4.4

In addition to updating jQuery, Drupal 7 will also ship with jQueryUI 1.8. jQueryUI is a smart addition which should help standardize many UI components, such as tabs, drag & drop events, or accordions. There are loads of Drupal modules which try to fulfill these tasks in Drupal 6. Therefore, standardizing around one UI library in Drupal 7 should make front-end development and maintenance easier.

Drupal 7 Ships with CCK

CCK is the Drupal equivalent of WordPress' custom post types

For those unfamiliar with Drupal, CCK stands for Content Construction Kit, and it is one of the coolest features of Drupal. While CCK used to be an add-on module, it is now included with Drupal 7 by default.

Essentially, CCK allows you to quickly create new content types, such as an article, blog post, or even music album. You can easily add fields to your content type using the administrative interface. For example, you could add Album Name, Tracks, Producer and release year to a music album content type. Once the content type is created with the appropriate fields, content contributors can start entering in content while you work on the technical parts of the site! If that explanation didn't get you excited about content types, check out this quick video:



A video demonstrating the Content Construction Kit:

RDF Support

Drupal 7 is the first major CMS to implement RDF.

Have you heard of the Semantic Web, otherwise known as the Giant Global Graph? According to Wikipedia, the semantic web is a group of methods and technologies to allow machines to understand the meaning - or 'semantics' - of information on the World Wide Web. In practice, the semantic web should vastly improve search engines, mashups, and data mining.

But what technology is used to implement the semantic web on our sites? That technology is called RDF. Drupal 7 is the first major CMS to implement RDF.

If you haven't heard of RDF yet, and remain unconvinced of its usefulness, I would highly recommend you watch the following video from DrupalCon to get an idea for what RDF can do for your site: The story of RDF in Drupal 7 and what it means for the Web at large.

Conclusion

This article has covered many of the most exciting features of Drupal 7, but there's even more! For those interested in Drupal module development, Fields are being overhauled and should make the creation of modules even simpler. Installation profiles have become easier to create and maintain. What are you favorite features of Drupal 7? Tell us in the comments!

Download Drupal 7.

Envato Tuts+: Intro to Drupal: Build a Simple CMS

Drupal's popularity has lately been rising. It's a great platform for setting up content management systems and community driven sites. Here, I'll give a general overview of Drupal and build a simple site for a fake client. We'll begin with outlining the client's needs, installing and configuring a few modules, creating user roles and assigning permissions, and finally we'll add in some content. We won't go into theming, as it's a bit out of the scope of this article.

1. A fake client

Let's start off with a fake client.

SmartMarks is a small marketing consulting firm, with 4 employees. Each employee would like their own blog. The site will need a few pages in addition to the blogs:

  • Home
  • About
  • Contact
  • Links
  • Blogs

Shannon, the business owner, wants full control over the site. The rest of the employees (Bill, Jean, and Terry) should only be able to write blog entries, but Bill may publish links.

The contact us form will accept the user's name, phone, email, and a short message. Submissions of the contact form should be sent only to Shannon.

Sounds pretty simple, huh? Well with Drupal, a lot of this core functionality is already built in. We'll use as much of the core functionality as we can, and we'll add in a few other modules to make building this site a breeze!

2. Install some stuff

First, start out by installing Drupal. I'll be developing this one on my local machine, but you can install it anywhere you wish. For this tutorial, I'll be working with Drupal 6.x.

To install Drupal, simply download (https://drupal.org) and unpack it, create your database, and visit http://localhost/ (or your own dev URL). Installation should be relatively simple for ya.

Image removed.Image removed.Image removed.

You'll need to create a config file. You can copy /webroot/sites/default/default.settings.php to /webroot/sites/default/settings.php. Be sure to make it writable to the server. Also, leave a copy of sites/default/default.settings.php where it is; Drupal will use it during installation.

Image removed.Image removed.Image removed.

After your config file is created, you can go ahead and install Drupal.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

On the next screen, you'll setup the first account for the site. This is the main administrator, or super user. This user will have permission to do anything and everything on the site.

Image removed.Image removed.Image removed.

And you can go ahead and specify a few server settings. If your server is configured for mod_rewrite URL rewriting, then you can go ahead and enable Clean URLs now. This will change your URLs from something like /?q=node/3 to just /node/3.

Image removed.Image removed.Image removed.

After successful installation, you can visit the site and login as the superuser.

Image removed.Image removed.Image removed.

3. Get some modules

For this site, we'll be using a few contributed modules. We'll have to download those and activate them before we can use them.

All modules that you'll install will be placed in the directory /webroot/sites/all/modules. If the modules directory doesn't exist there, just make a new one and name it modules.

Make sure to download the modules compatible with the version of Drupal that you're using. I'm using Drupal 6.x.

4. Admin Menu

This module is a must have for working with Drupal. It's not totally necessary, but it will save you loads of time.

Download it over at http://drupal.org/project/admin_menu and place it in /webroot/sites/all/modules

PathAuto & Token

Next, go grab a copy of PathAuto and Token. PathAuto is a module that will have Drupal automatically generate nice URLs. PathAuto requires Token to work.

Meta Tags (Nodewords)

Originally titled NodeWords, the Meta Tags module allows users to specify common meta tags, like meta keywords and meta description.

Get a copy of this module over at http://drupal.org/project/nodewords

CCK (Content Construction Kit)

CCK allows you to easily create new content types, without ever having to write any code! We'll use this for the company's external links section.

Get CCK at http://drupal.org/project/cck

Views

The views module allows you to configure custom views for displaying content. They're very useful when you have complex content types and categories. Here we'll use Views to display Links.

Get the Views module at http://drupal.org/project/views

Install some modules

After you've downloaded and unpacked the above modules into /webroot/sites/all/modules, you can go ahead and install them.

Visit http://localhost/admin/build/modules to turn some of them on.

For this site, we'll need to install the following. Simply check the boxes and click "Save configuration".

  • Administration - Administration Menu
  • Core - Blog
  • Core - Contact
  • Core - Path
  • Content - Content
  • Content - Text
  • Other - Meta tags
  • Other - Pathauto
  • Other - Token
  • Views - Views
  • Views - Views UI

5. Content Types

Before we work with users and roles, we'll create our Links content type. Each Link will need a title, URL, and short description.

What's a node?

Almost every piece of content in Drupal is stored as a single node. All nodes have a title and an optional description. By creating content types, you can add fields to the content type to extend the node.

In our case, each Link will need one additional field that's not provided by default, the URL.

Create a Link content type

We'll create a content type called Link. We'll then add a field to the content type called URL.

Visit http://localhost/admin/content/types/add

In the name field, enter the human-readable name. In the type field, enter a unique name for the type. The system will use this name internally. You can make it up, but generally it'll look like a variable name, lowercase and underscored. Also enter a short description of the content type.

Image removed.Image removed.Image removed.

Next we'll modify slightly this content type from the general node. In the "Submission form settings" group, instead of "Body", we'll title the body field "Short Description".

Image removed.Image removed.Image removed.

Next, we'll edit the "Workflow settings." Allow the link to be published by default, and disable automatic promotion to the front page.

Image removed.Image removed.Image removed.

And finally, disable comments on the Links.

Image removed.Image removed.Image removed.

Save the content type. If you visit the "Create Content" page, you'll now see the new content type, Link.

Image removed.Image removed.Image removed.

Additional fields with CCK

So we've got our base Link content type set up. But we need to add an additional field to each Link: URL. Visit http://localhost/content/types and "Manage fields" for content type Link.

Image removed.Image removed.Image removed.

Add a field titled "url", and name it "field_url". Choose text data and text field.

Image removed.Image removed.Image removed.

Save it. Another page will come up, with some more options. The defaults are ok for this, so just contine by clicking "Save field settings". After this, the Link content type should appear like this:

Image removed.Image removed.Image removed.

6. Views

Now let's set up a view for our new content type, Links.

Views can become quite complex, but for our example, we'll keep it very simple. We'll make a page view that displays Links. Plain and simple

Visit http://localhost/admin/build/views to get started. Click the tab "Add" to create a new view.

Image removed.Image removed.Image removed.

Name the view "Links" and choose type node.

Image removed.Image removed.Image removed.

The next few pages can grow quite complex, but be paitent. A bit of practice will get you more comfortable with views.

Firstly, we'll want our Links view to be a full page. So add a page display.

Image removed.Image removed.Image removed.

We'll have to make some settings next. Change the name and title of the view to Links. Set the "Row Style" to node, and choose to display teaser and links.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

Make sure you're clicking "Update Default Display" every time.

Set the Path to "links". This will be the URL path and our page view will show up at http://localhost/links.

Then set a menu for the view. Choose "Normal menu entry", title it Links, and put it into Primary Links. (More on menus a bit later).

Image removed.Image removed.Image removed.

The Basic Settings area should be similar to this by now:

Image removed.

And finally for the view, we'll need to setup a filter. The filter will allow us to restrict the view to only display nodes of type "link".

Add a filter by using the "+" button at the top of the Filters box.

Image removed.

Scroll down until you find the filter titled "Node: Type". Check it's box, then add it as a filter.

Image removed.Image removed.Image removed.

Choose a node type of "Link".

Image removed.Image removed.Image removed.

At this point, our whole view should look very simliar to the following.

Image removed.Image removed.Image removed.

Save the view. We'll come back to it later.

7. Users, Roles, & Permissions

Next we'll set up some user roles and permissions, and then we'll create some real users. Refer to the site requirements above to refresh on what our users need to be able to do.

User settings

Only SmartMarks staff will be able to have accounts. Public registration will not be necessary for this site. So we need to restrict regsitration at http://localhost/admin/user/settings and disallow public registration.

Image removed.Image removed.Image removed.

Roles

We'll need a couple of roles. Since Shannon wants full control, we'll need an Admin role. Since Bill can modify certain things that others can't we'll setup a Manager role. And finally, the rest of SmartMarks' employees will need to belong to an Employee role.

Visit http://localhost/admin/user/roles to get started.

Create a role titled Admin.

Image removed.Image removed.Image removed.

Repeat the process to create two more roles, Manager and Employee. We should have something like this now.

Image removed.Image removed.Image removed.

Perimssions

Next, we'll define permissions for each of the roles. Visit http://localhost/admin/user/permissions to set up permissions. Set them up like so.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

Image removed.Image removed.Image removed.

You may be wondering why we didn't give Manager too many permissions. This is because we'll set Bill to also be part of the Employee role, so Manager simply needs to be able to add and edit links. All of the permissions associated with Employee will be granted to Bill.

Now that we've got roles and permissions going, we can create our sites' users.

User Role Shannon Admin Bill Employee, Manager Jean Employee Terry Employee

Go ahead and create these users at http://localhost/user/user/create, assigning roles to each of them. We should end up with something like this on http://localhost/admin/user/user:

Image removed.Image removed.Image removed.

8. Creating Content... Finally!

And finally we can start creating content. We're well over halfway done at this point.

Create pages

First off, let's begin with the home page. Visit http://localhost/content/add to create a new Page.

Image removed.Image removed.Image removed.

Enter the page title and some sample content for the home page. Set up a menu item for this page. You may also enter some meta tag info if you'd like.

Image removed.Image removed.Image removed.

Leave the URL alias setting alone. We'll let Pathauto handle it, and we'll set that up shortly.

Image removed.Image removed.Image removed.

Save the page and create another for the About page.

Image removed.Image removed.Image removed.

If you now visit the main page, you'll notice that we've got a menu already going. These items come from the pages we just made and from the view we made for Links earlier.

Create some Links

Next, we'll create a few links. Visit the create content page again, but this time choose Link. Create a few links.

Image removed.Image removed.Image removed.

After we've created a few links, we can visit the view for Links. Visit http://localhost/links to see our links. Here's what I've got. Remember this is coming from the view we made earlier.

Image removed.Image removed.Image removed.

Contact form

Drupal's built-in Contact module is totally sufficient for SmartMarks. We'll just need to set it up. Visit http://localhost/admin/build/contact and click "Add Category" to begin.

Add a category for "General Enquiries", enter Shannon's email as the only recipient, and set "Selected" to yes. This will cause this category to be the default for the contact form. (You could setup multiple categories to handle contact submissions for areas such as Sales, Support, etc.)

Image removed.Image removed.Image removed.

You may now view your contact form at http://localhost/contact

Create some blog entries

Last of the content, we'll make a few sample blog entries. We could log out, and then log back in as each user individually, creating a blog entry under each. Or, since you're already logged in as superuser, you can create a few entries and change the author to each user.

Visit http://localhost/node/add/blog and create a sample entry.

Image removed.Image removed.Image removed.

Under the authoring info, enter shannon. This entry will become Shannon's first blog entry.

Image removed.Image removed.Image removed.

Repeat that to create a blog entry for the other users (bill, terry, jean). Then visit http://localhost/blog to see the user blogs.

Image removed.Image removed.Image removed.

9. Finishing touches

We still have a few things to tidy up before we're done. We need to setup pathauto to handle automatic URL aliases, finish our menu, check out each user account, and then we'll add a few blocks to demonstrate a little about blocks.

Menus

Let's start with menus. We've already created a few menu items beneath the Primary Links menu. We did this when we created the view for Links and when we created each static page.

Visit http://localhost/admin/build/menu. Here you'll see several menus available. Choose Primary Links.

Image removed.Image removed.Image removed.

Choose "Add item". We'll create an item for the Contact form.

Image removed.Image removed.Image removed.

Note that the path is relative to the site root. So don't enter "/contact"; just enter "contact".

Repeat the above to create another menu item for user blogs, using a path of "blog". Then visit the tab "List items" to view all the menu items within the Primary Links menu. Now we can reorder the items using the drag and drop handles on the left.

Image removed.Image removed.Image removed.

Make sure to save!!!

Now our primary links in the header should be complete and sorted.

Image removed.Image removed.Image removed.

Pathauto

Next up, we'll setup pathauto to handle our nice URLs. Visit http://localhost/admin/build/path.

Before we configure paths, let's remove any existing URL aliases. You can do this by visiting the tab "Delete Aliases", then just go ahead and choose all aliases and delete them.

Image removed.Image removed.Image removed.

Now we'll setup the automatic aliases under the tab "Automated alias settings".

Open up "Blog path settings" and check the box to have the system "Bulk generate aliases".

Image removed.Image removed.Image removed.

Now open up the "Node path settings." Here we'll set up a few rules to handle paths for different node types. Use the replacement patterns (this is where the Token module comes into play) to set up appropriate paths. Make sure your URL alias scheme will produce only unique URLs! And be sure to have it "Bulk generate aliases."

Image removed.Image removed.Image removed.

Then save. Then view "List" again. You should see new aliases made for all of our existing content.

Image removed.Image removed.Image removed.

A note about URL aliases: Don't forget to delete aliases if you change your URL scheme and regenerate aliases. Deleting and recreating aliases may seem a bit scary, but the more you do it, the more confident you'll become in your URL scheme.

Blocks

Shannon just informed us that she wants the site to highlight the company's recent office move. This is a good opportunity to go over blocks.

A block in Drupal is simply a 'chunk' of content, be it a list of nodes, some static HTML, a few images, or whatever. We'll set up a simple block to hold the notice about the office move.

Visit http://localhost/admin/build/block. Add a new block by using the tab "Add block".

Image removed.Image removed.Image removed.

After adding a block, you'll have to assign it to a region for display. Assign it to the left sidebar on http://localhost/admin/build/block, and don't forget to save!!!

Image removed.Image removed.Image removed.

You may also sort them with the drag handles, like menu items.

Image removed.Image removed.Image removed.

You should now see the new block displayed in the left sidebar after save.

Image removed.Image removed.Image removed.

Check user accounts

Now we're almost there. Just want to login as the users to make sure they've got the right permissions and that they can access the links to allow them to get stuff done.

Log out of the system and log back in as Shannon. Shannon is our administrator, so let's make sure she's able to create/edit all content. After logging in as Shannon, we should see a link to create content.

Image removed.

Go through and login as each user. Just take a look to make sure each one has the permissions and links available to get stuff done. If they don't, try going back to administer user permissions, and verify that they've been granted the correct permissions. Or also make sure you've correctly assigned roles.

Set the home page

We also need to tell Drupal to use our home page as the default home page. You can do this under http://localhost/admin/settings/site-information.

Before you change this data, though, we need to grab the node id of our home page. Visit our welcome page at http://localhost/welcome-smartmarks. Click or mouse-over the "Edit" tab; we just need the node's ID.

Image removed.Image removed.Image removed.

Our home page has a node id of 1, so we'll use that for the default home page. Visit http://localhost/admin/settings/site-information and enter some data. At the bottom, you'll see a field for the default home page. Enter "node/1". Note that we're using the node id becuase of pathauto. If we were to change the URL alias of the home page, then we won't have to change its node id, since it will remain the same. Drupal will automatically print out the correct URL alias.

Image removed.Image removed.Image removed.

10. Summary

This overview only scratches the surface of what Drupal can do. Hopefully I've given you a good overview of how to get started with the system in building this very simple CMS.

Themes

Drupal supports multiple themes, and each user can even chose their own theme.

Building a custom theme is out of the scope of this tutorial. But you can download and install some contributed themes. A good starting place is over at Theme Garden. Download and unpack themes into /webroot/sites/all/themes, then enable and configure them at http://localhost/admin/build/themes. Note that whenever you activate a new theme, you'll have to visit the blocks page to assign blocks to the theme's regions.

If you're ready to start building a theme, you might want to check out the Theme Guide.

Good luck!

Good luck in your Drupal ventures, and feel free to ask questions! Also check out http://drupal.org for more information and helpful articles.

ImageX: The Joy of Giving Back to Drupal: Celebrating Contribution

Drupal boasts a vibrant community of people passionate about making the project thrive in every way. As active members of this community, we at the ImageX team are excited to give back to Drupal. Outside of code contribution, ImageX has sponsored numerous DrupalCon events, and team members regularly help organize the Vancouver DrupalCafe and are lead organizers for the largest Drupal event in Europe (outside of DrupalCon), DrupalCamp Kyiv.  Our experts have shared their skills through sessions and webinars, along with Promote Drupal and other Committees at DrupalCons.

OpenSense Labs: An overview of Automatic Updates in Drupal 10

An overview of Automatic Updates in Drupal 10 Maitreayee Bora Wed, 11/30/2022 - 18:16

Between November 2020 and October 2021, 5212 organizations worldwide experienced data breaches. (source: statista).

And the number is steadily increasing. 

While every business that operates online faces some cyber threats, there are many ways to prevent data breaches or at least minimize their impact.

Delays before security updates are applied on site can result in compromised sites as seen in Drupalgeddon.

Manually updating a Drupal site can be an expensive, difficult, & time-consuming. 

The goal of the Automatic Updates Initiative is to provide safe and secure automatic updates for Drupal sites. It aims to solve the problem of any security concerns while over ridding the troublesome manual update process of a Drupal site.

Explained: Drupal Automatic Updates

Drupal’s Automatic Updates focus on resolving some of the most difficult usability concerns in maintaining Drupal websites. It is listed as one of the Drupal Core Strategic Initiatives for Drupal 9. 

It comprises of updates on production, development, and staging environments, with some integrations required in existing CI/CD processes. 

Automatic Updates in Drupal offers some major benefits to its users such as a reduction in the total cost of ownership (TCO) for Drupal websites and also a decrease in the maintenance cost.

Presently, we get to see a stable release that comprises features such as public safety alerts and readiness checks which will be discussed below. 

Importance of updating website

Here is the importance of updating a website. Take a look below:

  • Helps in increasing brand exposure

If we update a website by changing the outdated information with newly updated content then it will lead to an increase in brand exposure. But if we do not take this responsibility of updating content then it can be an obstacle in increasing the brand exposure which is essentially important.

  • Increases security

One of the major reasons for updating a website can be security concerns. For example, if a website is hacked then it can bring trouble for both the business and clients. But if we frequently update our website with the latest security features then such troubles of website hacking can be avoided. 

  • Provides mobile-friendly facility

By updating our website to a mobile-friendly website we enable our users to go through our website across various devices and platforms with ease and comfort. This leads to an increase in website traffic also resulting in a better company reputation.

Image removed.

Key Features of the Automatic Updates Module 

Here’s a list of features in the Automatic Updates module.  

  • Update readiness checks

We might not be always capable of updating all websites. Therefore, in instances like such, the readiness checks, one of the key features of Automatic Updates helps in identifying if a website is ready for updating automatically after a new release is offered to the Drupal community. 

For instance, websites that have un-run database updates, not having sufficient disk space for updating, or working on read-only file systems, won’t be able to get automatic updates. And if our website fails readiness checks and a Public service announcement (PSA) happens to be released, then it is essentially important to solve the readiness issue so that the website can be updated instantly.

  • In-place updates
  1. After the PSA service provides a notification to a Drupal site owner of an available update, and also the readiness checks happen to confirm that the website is ready to be updated, the website administrator is then able to update through the Update form.
     
  2. Tarball-based installations are well supported by this particular module and it doesn’t happen to choose some of the requirements in order to secure updating, rollback, etc which will come under the core solution.
     
  3. This module doesn’t support contrib updates or composer-based site installations. And also, the work on composer integration has begun already and is in progress.
  • Public service announcements (PSAs)

We get to see that infrequent announcements are done especially for critical security releases in regard to core and contrib modules. After a PSA is released, site owners need to review their websites so that they are updated well with the latest releases. Also, the website needs to be in a good position in order to quickly update if any fixes are given to the community.

Here is a quick video on the above-discussed features of automatic updates.


Conclusion

The Drupal community never fails to make an honest effort in building a community where its users can be benefited by making their software and websites safer and more user-friendly. The Automatic Updates initiative is a great example of it and by far it has made tremendous progress that cannot be unseen. 
 

Image removed.Articles Off