Envato Tuts+: Drupal 8: Properly Injecting Dependencies Using DI
As I am sure you know by now, dependency injection (DI) and the Symfony service container are important new development features of Drupal 8. However, even though they are starting to be better understood in the Drupal development community, there is still some lack of clarity about how exactly to inject services into Drupal 8 classes.
Many examples talk about services, but most cover only the static way of loading them:
1 $service = \Drupal::service('service_name');This is understandable as the proper injection approach is more verbose, and if you know it already, rather boilerplate. However, the static approach in real life should only be used in two cases:
- in the .module file (outside of a class context)
- those rare occasions within a class context where the class is being loaded without service container awareness
Other than that, injecting services is the best practice as it ensures decoupled code and eases testing.
In Drupal 8 there are some specificities about dependency injection that you will not be able to understand solely from a pure Symfony approach. So in this article we are going to look at some examples of proper constructor injection in Drupal 8. To this end, but also to cover all the basics, we will look at three types of examples, in order of complexity:
- injecting services into another of your own services
- injecting services into non-service classes
- injecting services into plugin classes
Going forward, the assumption is that you know already what DI is, what purpose it serves and how the service container supports it. If not, I recommend checking out this article first.
ServicesInjecting services into your own service is very easy. Since you are the one defining the service, all you have to do is pass it as an argument to the service you want to inject. Imagine the following service definitions:
1 services: 2 demo.demo_service: 3 class: Drupal\demo\DemoService 4 demo.another_demo_service: 5 class: Drupal\demo\AnotherDemoService 6 arguments: ['@demo.demo_service']Here we define two services where the second one takes the first one as a constructor argument. So all we have to do now in the AnotherDemoService class is store it as a local variable:
1 class AnotherDemoService { 2 /** 3 * @var \Drupal\demo\DemoService 4 */ 5 private $demoService; 6 7 public function __construct(DemoService $demoService) { 8 $this->demoService = $demoService; 9 } 10 11 // The rest of your methods 12 }And that is pretty much it. It's also important to mention that this approach is exactly the same as in Symfony, so no change here.
Non-Service ClassesNow let's take a look at classes that we often interact with but that are not our own services. To understand how this injection takes place, you need to understand how the classes are resolved and how they are instantiated. But we will see that in practice soon.
ControllersController classes are mostly used for mapping routing paths to business logic. They are supposed to stay thin and delegate heavier business logic to services. Many extend the ControllerBase class and get some helper methods to retrieve common services from the container. However, these are returned statically.
When a controller object is being created (ControllerResolver::createController), the ClassResolver is used to get an instance of the controller class definition. The resolver is container aware and returns an instance of the controller if the container already has it. Conversely, it instantiates a new one and returns that.
And here is where our injection takes place: if the class being resolved implements the ContainerAwareInterface, the instantiation takes place by using the static create() method on that class which receives the entire container. And our ControllerBase class also implements the ContainerAwareInterface.
So let's take a look at an example controller which properly injects services using this approach (instead of requesting them statically):
1 /** 2 * Defines a controller to list blocks. 3 */ 4 class BlockListController extends EntityListController { 5 6 /** 7 * The theme handler. 8 * 9 * @var \Drupal\Core\Extension\ThemeHandlerInterface 10 */ 11 protected $themeHandler; 12 13 /** 14 * Constructs the BlockListController. 15 * 16 * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler 17 * The theme handler. 18 */ 19 public function __construct(ThemeHandlerInterface $theme_handler) { 20 $this->themeHandler = $theme_handler; 21 } 22 23 /** 24 * {@inheritdoc} 25 */ 26 public static function create(ContainerInterface $container) { 27 return new static( 28 $container->get('theme_handler') 29 ); 30 } 31 }The EntityListController class doesn't do anything for our purposes here, so just imagine that BlockListController directly extends the ControllerBase class, which in turn implements the ContainerInjectionInterface.
As we said, when this controller is instantiated, the static create() method is called. Its purpose is to instantiate this class and pass whatever parameters it wants to the class constructor. And since the container is passed to create(), it can choose which services to request and pass along to the constructor.
Then, the constructor simply has to receive the services and store them locally. Do keep in mind that it's bad practice to inject the entire container into your class, and you should always limit the services you inject to the ones you need. And if you need too many, you are likely doing something wrong.
We used this controller example to go a bit deeper into the Drupal dependency injection approach and understand how constructor injection works. There are also setter injection possibilities by making classes container aware, but we won't cover that here. Let's instead look at other examples of classes you may interact with and in which you should inject services.
FormsForms are another great example of classes where you need to inject services. Usually you either extend the FormBase or ConfigFormBase classes which already implement the ContainerInjectionInterface. In this case, if you override the create() and constructor methods, you can inject whatever you want. If you don't want to extend these classes, all you have to do is implement this interface yourself and follow the same steps we saw above with the controller.
As an example, let's take a look at the SiteInformationForm which extends the ConfigFormBase and see how it injects services on top of the config.factory its parent needs:
1 class SiteInformationForm extends ConfigFormBase { 2 3 ... 4 public function __construct(ConfigFactoryInterface $config_factory, AliasManagerInterface $alias_manager, PathValidatorInterface $path_validator, RequestContext $request_context) { 5 parent::__construct($config_factory); 6 7 $this->aliasManager = $alias_manager; 8 $this->pathValidator = $path_validator; 9 $this->requestContext = $request_context; 10 } 11 12 /** 13 * {@inheritdoc} 14 */ 15 public static function create(ContainerInterface $container) { 16 return new static( 17 $container->get('config.factory'), 18 $container->get('path.alias_manager'), 19 $container->get('path.validator'), 20 $container->get('router.request_context') 21 ); 22 } 23 24 ... 25 }As before, the create() method is used for the instantiation, which passes to the constructor the service required by the parent class as well as some extra ones it needs on top.
And this is pretty much how the basic constructor injection works in Drupal 8. It's available in almost all class contexts, save for a few in which the instantiation part was not yet solved in this manner (e.g. FieldType plugins). Additionally, there is an important subsystem which has some differences but is crucially important to understand: plugins.
PluginsThe plugin system is a very important Drupal 8 component that powers a lot of functionality. So let's see how dependency injection works with plugin classes.
The most important difference in how injection is handled with plugins is the interface plugin classes need to implement: ContainerFactoryPluginInterface. The reason is that plugins are not resolved but are managed by a plugin manager. So when this manager needs to instantiate one of its plugins, it will do so using a factory. And usually, this factory is the ContainerFactory (or a similar variation of it).
So if we look at ContainerFactory::createInstance(), we see that aside from the container being passed to the usual create() method, the $configuration, $plugin_id, and $plugin_definition variables are passed as well (which are the three basic parameters each plugin comes with).
So let's see two examples of such plugins that inject services. First, the core UserLoginBlock plugin (@Block):
1 class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterface { 2 3 ... 4 5 public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteMatchInterface $route_match) { 6 parent::__construct($configuration, $plugin_id, $plugin_definition); 7 8 $this->routeMatch = $route_match; 9 } 10 11 /** 12 * {@inheritdoc} 13 */ 14 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { 15 return new static( 16 $configuration, 17 $plugin_id, 18 $plugin_definition, 19 $container->get('current_route_match') 20 ); 21 } 22 23 ... 24 }As you can see, it implements the ContainerFactoryPluginInterface and the create() method receives those three extra parameters. These are then passed in the right order to the class constructor, and from the container a service is requested and passed as well. This is the most basic, yet commonly used, example of injecting services into plugin classes.
Another interesting example is the FileWidget plugin (@FieldWidget):
1 class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface { 2 3 /** 4 * {@inheritdoc} 5 */ 6 public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, ElementInfoManagerInterface $element_info) { 7 parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings); 8 $this->elementInfo = $element_info; 9 } 10 11 /** 12 * {@inheritdoc} 13 */ 14 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { 15 return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['third_party_settings'], $container->get('element_info')); 16 } 17 ... 18 }As you can see, the create() method receives the same parameters, but the class constructor expects extra ones that are specific to this plugin type. This is not a problem. They can usually be found inside the $configuration array of that particular plugin and passed from there.
So these are the main differences when it comes to injecting services into plugin classes. There's a different interface to implement and some extra parameters in the create() method.
ConclusionAs we've seen in this article, there are a number of ways we can get our hands on services in Drupal 8. Sometimes we have to statically request them. However, most of the time we shouldn't. And we've seen some typical examples of when and how we should inject them into our classes instead. We've also seen the two main interfaces the classes need to implement in order to be instantiated with the container and be ready for injection, as well as the difference between them.
If you are working in a class context and you are unsure of how to inject services, start looking at other classes of that type. If they are plugins, check if any of the parents implement the ContainerFactoryPluginInterface. If not, do it yourself for your class and make sure the constructor receives what it expects. Also check out the plugin manager class responsible and see what factory it uses.
In other cases, such as with TypedData classes like the FieldType, take a look at other examples in core. If you see others using statically loaded services, it's most likely not yet ready for injection so you'll have to do the same. But keep an eye out, because this might change in the future.
Envato Tuts+: What Is Drupal?
Drupal is a popular open-source content management system written in PHP. Having been created in the early 2000s by a Belgian student, it now powers some of the most prominent websites on the web (WhiteHouse.gov, Weather.com, etc.). It is often regarded as a competitor of CMSs such as WordPress and Joomla.
One of the most important components of the Drupal project is its community of supporters (contributors, developers, evangelists, business owners, etc.). Prominent within this community stands the Drupal Association, responsible for "fostering and supporting the Drupal software project, the community and its growth".
A giant leap from its predecessor, the 8th major release of the Drupal project has just hit the shelves. It brought about a serious modernisation of its code, practices and mentality. Many regard this shift as a real move away from the traditional notion of a CMS to more of a Content Management Framework (CMF) that provides a great platform for building complex applications.
In this article, I'm going to answer some of the more frequent questions people have about Drupal when starting up for the first time or considering doing so:
- Is it right for me? Who is it aimed at?
- How can it be installed, and where can I host it?
- How can I start working with it as a developer?
- What options do I have for extending functionality or styling it?
Since the beginning of the project, Drupal has evolved from being mainly a tool for building smaller sites to one that can now power enterprise-level platforms. Especially with Drupal 8, site builders and developers can easily scale up from small websites to large platforms with many integrations. For example, the adoption of Composer allows you not only to bring external libraries into a Drupal project, but also to use Drupal as part of a bigger project of applications and libraries. It's safe to say that Drupal is flexible enough to meet the needs of a wide range of projects.
When it comes to development, Drupal has always had a relatively closed community—not because people are unfriendly, quite the contrary, but mainly because of the code typically being written in a Drupal way (resulting in what sometimes is referred to as Drupalisms). This has meant a learning curve for any developer starting up, but also less interest from developers of other PHP projects to jump in and contribute.
This is no longer the case. Especially with the release of Drupal 8, the community now promotes a new mentality of code reusability and best practice across different open-source projects. Active participation in the PHP Framework Interoperability Group is part of this effort, and using a number of popular Symfony components in Drupal 8 core is a testament to this commitment.
With this move, the Drupal community has gotten richer by welcoming many developers from other communities and projects, and it is sure to grow even further. So if you are a Laravel developer, looking at Drupal code will no longer be so daunting.
How Can I Install Drupal, and Where Can I Host It?Traditionally, Drupal has had a relatively easy installation process, particularly for people who at least knew their way around a Linux environment. The project simply needs to be dropped into a folder your web server can run (which needs to be using PHP and have a MySQL or MariaDB database). Then pointing your browser to the /install.php file and following the steps takes care of the rest. The most important screen you'll see is the one in which you select a specific database to use.
In terms of requirements, the LAMP stack (Linux, Apache, MySQL and PHP) environment has always been a favourite for Drupal to run in. However, it is in no way restricted to it. Solutions exist for installing it straight on Windows or Mac (e.g. using the Acquia Dev Desktop) but also on a Linux system that runs other web servers.
The easiest approach, if you go with your own setup, is to use a LAMP server for hosting. For a bit more performance you can replace Apache with Nginx, but you'll then have to take care of some specific configuration that otherwise is handled in the .htaccess file Drupal ships with.
However, if you don't want the hassle of maintaining your own hosting server, there are three main providers of specialised Drupal managed hosting: Acquia, Pantheon, and Platform.sh. These also provide a workflow for easy updates and development flow. Past that, you are looking at fully managed hosting with a Drupal development company.
How Can I Get Started Developing for It?Developing Drupal websites has typically been the kind of thing you either liked a lot or didn't like at all. This is because when you were first introduced to Drupal, you encountered very many specificities that you didn't see in other projects. So if those tickled your fancy, you loved it forever.
With getting off this island in Drupal 8, this is no longer the case as much. You still have plenty of Drupalisms left that you can love or hate, but you now also have external components like Symfony or Guzzle and, most importantly, a more modern way of writing code in general (OOP, design patterns, reusable components, etc.). So your PHP skills from building websites with Zend will come in handy.
A good way of getting into Drupal development is to follow some online video courses. There are a couple of resources that are excellent for this purpose, most notably Drupalize.me. If, however, video is not your favourite medium, there are also many written tutorials and guides available to get you started. Check out the following links for some of the first steps you can take:
- Official Drupal development guides
- The Drupal API reference
- Module development guides
- Envato's Drupal Code Tutorials
Since Drupal 8 is brand new, you'll find significantly more learning content for Drupal 7. Nevertheless, the focus in the community has been shifting recently towards Drupal 8, so you can expect more and more of these resources to crop up. And if you have no experience with any version of Drupal, it's best to focus exclusively on Drupal 8 as the changes between the two are big and perhaps you'd be facing unnecessary challenges.
How Can I Extend Drupal?The main extension point of a core Drupal installation is its module system.
Modules are used to encapsulate bigger chunks of reusable functionality that can/should work on different sites. Aside from the core modules, there are a large number of contributed ones, available for installation.
Granted, most are still only for Drupal 6 and 7, but the community is catching up also for the newest version. This problem is also mitigated by the incorporation in Drupal 8 of a few popular contributed modules as well as extending the scope of what core can do out of the box (compared to Drupal 7).
Lastly, custom modules (the ones that you write yourself) are the primary way you can add any functionality that you want and that is not available via a contributed module.
Installing modules can allow you to plug in various pieces of functionality, but you should not treat this as a green light for adding too many. It's always better to stick to the ones you actually need, and don't be afraid to be critical in this respect. You can also work on finding a good balance between contributed code and the custom one you write yourself.
Additionally, since we are talking about open-source software, you should always evaluate the modules you install. The following indicators are good examples to pay attention to: number of downloads and usage, commit frequency, maintainer engagement, state of the issue queue.
And do keep security in mind as well. It's highly recommended you keep both Drupal core and any contributed modules up to date as this will significantly help you keep your site and server secure (though it doesn't ensure it).
What About Styling?The styling layer of a Drupal site is handled (in large part) by its theme. Themes are similar to modules in that they are an extension point, but they have different responsibilities. They contain the styles, front-end libraries and in most cases template files that are used to output data.
There has been great progress in Drupal 8 compared to the previous version: the popular Twig engine has been adopted for templating, theming has been limited to Twig template files, debugging and overriding templates has been made much easier, etc. Similar to the advances in back-end development experience (DX), the theming layer has been made more appealing to the non-Drupal crowd. Front-end developers can now easily work with Drupal themes without having to understand the ins and outs of the back end.
Drupal core comes with a number of themes that can provide you with examples but also which you can extend from. There are also contributed themes similar to how there are modules. Popular front-end frameworks such as Bootstrap or Zurb Foundation have mature Drupal theme implementations for Drupal 7, which are also readying for Drupal 8. These work very well as base themes but also for quickly scaffolding a website and making it look decent.
Paid themes are also available to try out. Usually they are very cheap and quick to set up. The problem with them is that they are worth exactly as much as you pay for them and usually have gaping holes in their flexibility. As a beginner, these themes can seem like a great way to set up a site, and they very well may be. However, as you progress, you'll learn to avoid them and build your own, based on external designs or even plain HTML/CSS/JS templates.
ConclusionDrupal is a powerful tool for building websites and platforms of any kind. With each new major release, Drupal has shown a commitment to better itself, become more robust and flexible, and embrace outside communities as well.
Envato Tuts+: Using and Extending the Drupal 8 Mail API: Part 2
In the previous article we looked at how we can send emails programatically in Drupal 8. We also saw how other modules can alter these outgoing mails. Today, we are going to look at how we can use the Mail API to extend this default behaviour. The purpose is to use an external service as a means for email delivery.
For this, we will use Mandrill, although the focus of the article will not be its API or how to work with it, but rather the Drupal side of things. And remember, the working module can be found in this Git repository.
As we've seen in the previous article, sending an email in Drupal 8 happens by requesting the mail manager, passing some parameters to its mail() method, and setting up a template inside a hook_mail() implementation. What the mail manager does internally is load up the appropriate mail plugin, construct the email, and then delegate to the mail() method of whatever plugin was loaded.
But who does it actually delegate to?
Plugin SelectionAn important thing to understand before writing our own plugin is the selection process of the mail manager for loading plugins. In other words, how do we know which plugin it will load, and how can we make it load our own?
The system.mail.interface configuration array holds all the answers. It contains the ids of the available plugins, keyed by the context they are used in. By default, all we have inside this configuration is default => phpmail. This means that the plugin with the id phpmail (the PHPMail class) is used as fallback for all contexts that are not otherwise specified, i.e. the default.
If we want to write our own plugin, we need to add another element into that array with the plugin id as its value. The key for this value can be one of two things: the machine name of our module (to load the plugin whenever our module sends emails) or a combination of module name and email template key (to load the plugin whenever our module sends an email using that specific key).
An example of the latter construct is d8mail_node_insert, where d8mail is our module name we started building in the previous article, and node_insert is the email template key we defined.
So now that we know how the mail plugin selection happens, we need to make sure this config array contains the necessary information so that emails sent with our d8mail module use the new plugin we will build. We can do this inside a hook_install() implementation that gets triggered only once when the module gets installed:
d8mail.install:
1 /** 2 * Implements hook_install(). 3 */ 4 function d8mail_install() { 5 $config = \Drupal::configFactory()->getEditable('system.mail'); 6 $mail_plugins = $config->get('interface'); 7 if (in_array('d8mail', array_keys($mail_plugins))) { 8 return; 9 } 10 11 $mail_plugins['d8mail'] = 'mandrill_mail'; 12 $config->set('interface', $mail_plugins)->save(); 13 }Not super complicated what happens above. We load the editable config object representing the system.mail configuration, and add a new element to the interface array: d8mail => mandrill_mail. We will soon create a mail plugin with the id of mandrill_mail which will be used for all emails sent by the d8mail module. And that's it.
But before we move on, we need to make sure this change is reverted when the module is uninstalled. For this, we can use the counterpart hook_uninstall() that gets called when a module gets uninstalled (there is no more module disabling in Drupal 8).
Inside the same file:
1 /** 2 * Implements hook_uninstall(). 3 */ 4 function d8mail_uninstall() { 5 $config = \Drupal::configFactory()->getEditable('system.mail'); 6 $mail_plugins = $config->get('interface'); 7 if ( ! in_array('d8mail', array_keys($mail_plugins))) { 8 return; 9 } 10 11 unset($mail_plugins['d8mail']); 12 $config->set('interface', $mail_plugins)->save(); 13 }With the hook_uninstall() implementation we do the opposite of before: we remove our plugin id if it is set.
The install/uninstall scenario is just one way to go. You can also create an administration form that allows users to select the plugin they want and under which context. But you still need to make sure that when you disable the module defining a particular plugin, the configuration will no longer keep a reference to that plugin. Otherwise the mail manager may try to use a non-existent class and throw all kinds of errors.
MandrillAs I mentioned before, we will work with the Mandrill API in order to illustrate our task. So let's load up Mandrill's PHP Library and make it available in our environment. There are three steps we need to do for this.
First, we need to actually get the library inside Drupal. At the time of writing, this basically means adding the "mandrill/mandrill": "1.0.*" dependency to the root composer.json file and running composer install. Keep in mind, though, that this will also clear the Drupal installation from inside the core/ folder and download the latest stable release instead. Then, you'll need to edit the root index.php file and change the path to the autoloader as per these instructions. Hopefully this last action won't be necessary soon, and I encourage you to follow the discussions around the future of Composer in Drupal 8 for managing external libraries.
Second, we need to get an API key from Mandrill. Luckily, this we can easily generate from their administration pages. Once we have that, we can store it inside a new file created on our server, at either location:
1 ~/.mandrill.key 2 /etc/mandrill.keyWe can also pass the key as a constructor parameter to the main Mandrill class, but this way we won't have to hardcode it in our code.
Thirdly, we need to create a service so that we can use dependency injection for passing the Mandrill class into our plugin:
d8mail.services.yml:
1 services: 2 d8mail.mandrill: 3 class: MandrillDepending on how you have loaded the Mandrill class into your application, you'll need to change the value after class. By using the composer.json approach, this will suffice.
The Mail PluginIt's finally time to create our plugin. In Drupal 8, plugin classes go inside the src/Plugin folder of our module. Depending on their type, however, they are placed further down within other directories (in our case Mail). Let's write our class that will depend on the Mandrill API library to send emails:
src/Plugin/Mail/MandrillMail.php:
1 <?php 2 3 namespace Drupal\d8mail\Plugin\Mail; 4 5 use Drupal\Core\Mail\MailFormatHelper; 6 use Drupal\Core\Mail\MailInterface; 7 use Drupal\Core\Plugin\ContainerFactoryPluginInterface; 8 use Symfony\Component\DependencyInjection\ContainerInterface; 9 use Mandrill; 10 use Mandrill_Error; 11 12 /** 13 * Defines the Mandrill mail backend. 14 * 15 * @Mail( 16 * id = "mandrill_mail", 17 * label = @Translation("Mandrill mailer"), 18 * description = @Translation("Sends an email using Mandrill.") 19 * ) 20 */ 21 class MandrillMail implements MailInterface, ContainerFactoryPluginInterface { 22 23 /** 24 * @var Mandrill 25 */ 26 private $mandrill; 27 28 /** 29 * @param Mandrill $mandrill 30 */ 31 public function __construct(Mandrill $mandrill) { 32 $this->mandrill = $mandrill; 33 } 34 35 /** 36 * {@inheritdoc} 37 */ 38 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { 39 return new static( 40 $container->get('d8mail.mandrill') 41 ); 42 } 43 44 /** 45 * {@inheritdoc} 46 */ 47 public function format(array $message) { 48 // Join the body array into one string. 49 $message['body'] = implode("\n\n", $message['body']); 50 // Convert any HTML to plain-text. 51 $message['body'] = MailFormatHelper::htmlToText($message['body']); 52 // Wrap the mail body for sending. 53 $message['body'] = MailFormatHelper::wrapMail($message['body']); 54 55 return $message; 56 } 57 58 /** 59 * {@inheritdoc} 60 */ 61 public function mail(array $message) { 62 63 try { 64 $vars = [ 65 'html' => $message['body'], 66 'subject' => $message['subject'], 67 'from_email' => $message['from'], 68 'to' => array( 69 array('email' => $message['to']) 70 ), 71 ]; 72 73 $result = $this->mandrill->messages->send($vars); 74 if ($result[0]['status'] !== 'sent') { 75 return false; 76 } 77 78 return $result; 79 } 80 catch (Mandrill_Error $e) { 81 return false; 82 } 83 } 84 }There are a couple of things to note before getting into what the class does.
First, the annotations above the class. This is just the most common plugin discovery mechanism for Drupal 8. The id key matches the value we added to the system.mail.interface configuration array earlier, while the rest are basic plugin definition elements.
Second, the implementation of the ContainerFactoryPluginInterface interface by which we define the create() method. The latter is part of the dependency injection process by which we can load up the Mandrill service we defined in the services.yml file earlier. This makes testing much easier and it's considered best practice.
As I mentioned, the mail plugins need to implement the MailInterface interface which enforces the existence of the format() and mail() methods. In our case, the first does exactly the same thing as the PHPMail plugin: a bit of processing of the message body. So you can add your own logic here if you want. The latter method, on the other hand, is responsible for sending the mail out, in our case, using the Mandrill API itself.
As the Mandrill documentation instructs, we construct an email message inside the $vars array using values passed from the mail manager through the $message parameter. These will be already filtered through hook_mail(), hook_mail_alter() and the plugin's own format() method. All that's left is to actually send the email. I won't go into the details of using the Mandrill API as you can consult the documentation for all the options you can use.
After sending the email and getting back from Mandrill a sent status, we return the entire response array, which contains some more information. This array then gets added by the mail manager to its own return array keyed as result. If Mandrill has a problem, rejects the email or throws an exception, we return false. This will make the mail manager handle this situation by logging the incident and printing a status message.
And that is pretty much it. We can clear the cache and try creating another article node. This time, the notification email should be sent by Mandrill instead of PHP's mail(). With this in place, though, the hook_mail_alter() implementation has become superfluous as there are no headers we are actually sending through to Mandrill (and the text is HTML already). And for that matter quite a lot of the work of the mail manager is not used, as we are not passing that on to Mandrill. But this is just meant to illustrate the process of how you can go about setting this up. The details of the implementation remain up to you and your needs.
ConclusionAnd there we have it. We have implemented our own mail plugin to be used by the d8module we started in the previous article. And due to the extensible nature of Drupal 8, it didn't even take too much effort.
What's left for you to do is to perfect the mail sending logic and adapt it to your circumstances. This can mean further integration between Mandrill and your Drupal instance, constructing nice templates or what have you. Additionally, an important remaining task is writing automated tests for this functionality. And Drupal 8 offers quite the toolkit for that as well.
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: moduleWith 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).
ConclusionAnd 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
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.
PrerequisitesIn 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
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 TodayWe 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 DataSince 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:
Step 1: SetupDrupal 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:
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.moduleThe 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.
CheckpointNow, 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.
Step 3: Add the Like ButtonWe 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 FacebookThe 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.
Implement hook_node_viewThe 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_themeThis 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 FunctionFinally, 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.
CheckpointWe 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:
Step 4: Create the Sidebar BlockCreating 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_viewThe 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:
Wrapping UpI 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 ThemesThe 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 InterfaceOne 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:
- Grok Drupal 7 Theming
- D7 theming what's new
- Design and Theming: What's new in Drupal 7
- Converting 6.x themes to 7.x
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 CCKCCK 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.
ConclusionThis 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!
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 clientLet'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 stuffFirst, 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.
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.
After your config file is created, you can go ahead and install Drupal.
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.
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.
After successful installation, you can visit the site and login as the superuser.
3. Get some modulesFor 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 MenuThis 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 & TokenNext, 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.
- PathAuto - http://drupal.org/project/pathauto
- Token - http://drupal.org/project/token
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
ViewsThe 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 modulesAfter 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
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 typeWe'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.
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".
Next, we'll edit the "Workflow settings." Allow the link to be published by default, and disable automatic promotion to the front page.
And finally, disable comments on the Links.
Save the content type. If you visit the "Create Content" page, you'll now see the new content type, Link.
Additional fields with CCKSo 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.
Add a field titled "url", and name it "field_url". Choose text data and text field.
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:
6. ViewsNow 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.
Name the view "Links" and choose type node.
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.
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.
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).
The Basic Settings area should be similar to this by now:
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.
Scroll down until you find the filter titled "Node: Type". Check it's box, then add it as a filter.
Choose a node type of "Link".
At this point, our whole view should look very simliar to the following.
Save the view. We'll come back to it later.
7. Users, Roles, & PermissionsNext 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 settingsOnly 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.
RolesWe'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.
Repeat the process to create two more roles, Manager and Employee. We should have something like this now.
PerimssionsNext, we'll define permissions for each of the roles. Visit http://localhost/admin/user/permissions to set up permissions. Set them up like so.
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 EmployeeGo 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:
8. Creating Content... Finally!And finally we can start creating content. We're well over halfway done at this point.
Create pagesFirst off, let's begin with the home page. Visit http://localhost/content/add to create a new Page.
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.
Leave the URL alias setting alone. We'll let Pathauto handle it, and we'll set that up shortly.
Save the page and create another for the About page.
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 LinksNext, we'll create a few links. Visit the create content page again, but this time choose Link. Create a few links.
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.
Contact formDrupal'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.)
You may now view your contact form at http://localhost/contact
Create some blog entriesLast 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.
Under the authoring info, enter shannon. This entry will become Shannon's first blog entry.
Repeat that to create a blog entry for the other users (bill, terry, jean). Then visit http://localhost/blog to see the user blogs.
9. Finishing touchesWe 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.
MenusLet'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.
Choose "Add item". We'll create an item for the Contact form.
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.
Make sure to save!!!
Now our primary links in the header should be complete and sorted.
PathautoNext 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.
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".
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."
Then save. Then view "List" again. You should see new aliases made for all of our existing content.
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.
BlocksShannon 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".
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!!!
You may also sort them with the drag handles, like menu items.
You should now see the new block displayed in the left sidebar after save.
Check user accountsNow 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.
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 pageWe 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.
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.
10. SummaryThis 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.
ThemesDrupal 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.
Chromatic Insights: Drupal 7 End-of-Life Podcast - Episode 02
Chromatic Insights: The Drupal 7 End-of-Life Podcast - Episode 01
The Drop Times: TDT Is a Media Partner for DrupalSouth 2023
mandclu: Patching .htaccess for SEO
The Drop Times: TDT Is a Media Partner for DrupalCamp Poland
Axelerant Blog: Axelerant Wins India's Best Workplaces in Health And Wellness Award
Great Place To Work® has certified Axelerant as among India’s 40 Best Workplaces in Health & Wellness.
Cocomore: Right-to-Left script done right in Drupal
Cocomore: Recap DrupalCon Prague 2022
Drupal Association blog: Industry Summits are the place to be at DrupalCon Pittsburgh 2023
Co-authors: Vladimir Roudakov, Lisa McCray
The industry summits at DrupalCon are a great way to get the most out of your conference experience if you’re a government or higher education professional. Summits are full day sessions scheduled when there are no general conference sessions happening, so you won’t miss anything from the main event.
What are the registration details?Although the Summits are part of the DrupalCon program, they are separate events and require a separate registration. There is also an additional cost associated with Summit registration. It’s an additional $250, and you can add a summit package to regular registration all through one convenient platform.
Higher Education SummitWhether you are a web developer, administrator, or educator, you will gain valuable insights into how other institutions have used Drupal to improve their websites, streamline processes, and enhance the student experience. The Higher Ed Summit is the perfect meeting ground for folks doing Drupal in a higher education context. Pittsburgh is a huge Drupal higher education city, with both Carnegie Mellon University and University of Pittsburgh using Drupal!
When is it?Thursday, 8 June, 2023 from 9:00-16:00 EST
Who should attend?The DrupalCon Higher Education Summit is a must-attend summit for anyone working in the higher education sector. This summit provides a unique opportunity to network and collaborate with experts and professionals in the field. Attendees will have the chance to learn about the latest trends and best practices in higher education technology and hear from leading experts in the field.
Attending the DrupalCon Higher Education Summit is a great investment in your professional development. The summit provides a wealth of knowledge and resources that you can use to improve your skills and stay ahead of the curve in higher education technology. With a focus on cutting-edge technology, best practices, and real-world examples, the DrupalCon Higher Education Summit is a must-attend event for anyone looking to stay ahead in the fast-paced world of higher education technology.
What will I get by attending?One of the key benefits of attending the DrupalCon Higher Education Summit is the opportunity to learn from real-world case studies and practical applications. You will also have the chance to engage with peers and share your own experiences and challenges.
About those schools…Carnegie Mellon and Pitt are 14 and 10 minutes, respectively, away from the David L. Lawrence Convention center! Take a stroll through these historic campuses, where there’s a rich history of computer science and academic achievement. Both campuses have beautiful cathedrals with incredible architecture that make for the perfect peaceful afternoon.
Fountain outside of the Cathedral of Learning, Pitt
Image source: By Christopher Lancaster from Oshawa, Canada - 20080621_2744 Uploaded by crazypaco, CC BY-SA 2.0, https://commons.wikimedia.org/w/index.php?curid=6625882
Government SummitAre you a federal, state, or local government employee, or a private sector employee supporting the government?
- Would you like to meet up with Drupalers from all different skill levels in a variety of roles and talk about common issues you face while supporting government work?
- Do you dream of seeing one of the actual bikes used in the filming of PeeWee’s Big Adventure?
Will attending the DrupalCon Government Summit makes you feel this excited? Probably!
Image source: Wikimedia, Fair Use
Then I’ve got great news for you! We can help with two out of three of those! Yinz should make plans to attend the DrupalCon Pittsburgh Government Summit. We have a full day planned of government-y goodness that you won’t want to miss.
When is it?Thursday, 8 June, 2023 from 9:00-16:00 EST
Who should attend?The Government Summit is intended for anyone who uses Drupal in the context of government, whether it be at a local, state or federal level. All skill levels and roles are welcome. You’ll meet site builders, developers, themers, project managers, support specialists, and more.
What will I get by attending?This year we are returning to the full day format, and will be featuring a panel, case studies, presentations, and plenty of talk and discussion on topics such as approaches to content author training, the impact of accessibility work, how to design *with* Drupal’s strengths to support agency needs, and much much more! Specifics on presentations and topics are being ironed out now, so stay tuned for more detail.
In addition, similar to past years, part of our schedule will be dedicated to “unconference” table-talk time with interactive discussions on topics chosen by you, the attendees. We like to think of them as mini-BoFs. Tables can form to continue the discussions from earlier in the day or your own unique topics. Opportunities to suggest topics will be available throughout the morning.
But I really want to see that bike….While the Government Summit will sadly have a distinct lack of movie prop bicycles, you are in luck! It turns out that one of the 4 bikes used in the filming of the movie is on display just across the river at Bicycle Heaven, which, according to Wikipedia, is the largest transportation museum in the world dedicated to bicycles. It’s also free to visit, so if you want to see that bike or any of its approximately 3500 friends, roll on over and check it out!
MidCamp - Midwest Drupal Camp: Volunteer to Help at MidCamp!
Want to give back to the Drupal Community without writing a line of code? Volunteer to help out at MidCamp. We’re looking for amazing people to help with all kinds of tasks throughout the event including:
Setup/Teardown-
For setup, we need help making sure registration is ready to roll, getting hats ready to move, and getting the rooms and walkways prepped for our amazing sessions.
-
For teardown, we need to undo all the setup including packing up all the rooms, the registration desk, cleaning signage, and making it look like we were never there.
-
We need ticket scanners, program dispersers, and people to answer questions.
-
Pick your sessions and count heads, intro the speakers and make sure they have what they need to survive, and help with the in-room A/V (by calling our Fearless Leader / A/V Genius)
- We won't turn away any help, so if there's something you'd like to do to help out, just let us know!
This year we're going to be giving every volunteer credit on Drupal.org, so be sure to include your profile name when you sign up to volunteer.
If you’re interested in volunteering or would like to find out more, please reach out in the #volunteers channel on the MidCamp Slack.
Please see the embedded Volunteer Packet below for more details. Also, there will be a brief, online orientation leading up to the event to go over the volunteer opportunities more in detail.
Questions?tweet: @midcamp
email: info@midcamp.org
MidCamp - Midwest Drupal Camp: It’s spring in Chicago and MidCamp is almost here🙀
We’ve been busy… so busy we haven’t been able to tell you what’s been happening! Here’s everything you need to know about with MidCamp just 5 weeks away!
Health & SafetyWith help from the community, our venue, and outside professionals, we’ve completed the MidCamp 2023 Health & Safety Policy. The policy is rooted in our values but is reflective of current conditions and our capacity as a fully volunteer-led team.
We’ve done our best to get this published and sincerely hope this works for you, but if it doesn’t you may request a full refund of your ticket at any time prior to the event by emailing info@midcamp.org.
Session ScheduleWe’ve got a great line-up this year! All sessions on Wednesday and Thursday (April 26-27) are included in the price of your MidCamp registration. We encourage you to start plotting your days now -- and get ready for some great learning opportunities!
Our Commitment to Diversity and InclusionMidCamp is committed to being accessible to anyone and everyone who is interested in learning and participating in our community. We'll teach you, we'll feed you, and we'll welcome you with open arms. If you don't fit into any of our public ticket categories, we have an option for you. Get your sponsored ticket here.
Student ticketsKnow any students interested in learning about Drupal? We have discounted tickets ($25!) available for students to join us at MidCamp and learn more about the community! There are sessions for everyone—topics range from Site Building and DevOps to Project Management and Design.
Drupal Association blog: Women’s History Month Spotlight: Anneleen Demasure
It’s Women’s History Month, and all month long, we’ve been spotlighting incredible women in Tech on our Twitter and Linkedin page. Today, we’re bringing you an extended highlight of one of the most impressive women in tech today – Anneleen Demasure, CEO of Belgium-based digital experience agency Dropsolid.
Read on to hear Anneleen’s thoughts on being a woman in technology and her advice for other women who want to enter the field!
Drupal Association: What's it like to be a woman in technology?
Anneleen Demasure: Good question, as I do not think it is about woman versus man or about technological versus creative industries. For me, it is all about balance between male and female energy. The world these days is so complex that it needs both male and female energy.
I am most enjoying my time as a woman in technology when all different energies can flow in respect of each other. When my own male and female energy is in balance and stress is under control, I feel I can support the team and the company best, and that makes me happy.
I am lucky to work in a technological company, Dropsolid, where there is openness, transparency and both female and male energy on all levels which makes it much easier to address unbalances.
DA: What keeps you motivated in your career in technology?
AD: An important starting point for me is the psychological safety to be yourself at any time. Everyone has talents and personal strengths, but all strengths also have downsides to them. Feeling appreciated with your ups and your downs is crucial to flourish.
Next to that, the autonomy and freedom to be allowed to change things, the connection with colleagues, and making progress together keeps me motivated.
Often in technology, you're building something big together: when a team succeeds in doing that, it surely gives a boost.
DA: What's your favorite aspect of working in tech and/or Drupal?
AD: I guess what is precious to me is the feeling of jointly creating and developing something new which makes a customer happy (because it is of important value to them).
The co-creation, the joy of working together, and the impact are my favourite aspects of working in tech.
Too often, we see technology as wireframes or code or design where, in the end, they are (vital) solutions for people to be helped, to be heard, to find their way, to be unburdened...
All good technology should have this bigger purpose: a housing platform helps people to find a new home, a hospital platform helps people to find the right medical services, a tourism platform inspires you for your next holiday... So it is not about the perfect code or design but about what it brings to people in their daily life. At Dropsolid, Drupal is the means to accomplish this. And the fact that it's open without lock-in, makes it even better.
DA: What advice do you have for aspiring women business leaders?
AD: Whatever situation or crisis you're in, never lose your female energy as one of your drivers. We are dominantly trained and learned to take action and talk, but it often helps to step back and listen to yourself and to others. Finally, always trust your inner voice - it will not betray you.
We cannot thank Anneleen enough for chatting with us and giving such fantastic advice! For more from Anneleen, check out her recent blog post on Dropsolid.com, ‘A plea for wider inclusion and more feminine energy’.