Try Tuts+ Premium, Get Cash Back!
Create a Facebook Recent Activity Drupal Module

Create a Facebook Recent Activity Drupal Module

Tutorial Details
  • Program: Drupal, PHP
  • Version (if applicable): 7
  • Difficulty: Beginner
  • Estimated Completion Time: 30 - 45 min

Final Product What You'll Be Creating

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:

Final Product


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:


Final Product


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:

  ; the module's user friendly name, will be displayed in the modules list
  name = Facebook Recent Activity
  ; the module's description, will be displayed in the second column in the modules list
  description = Retrieves and displays in a block the recent activity data from Facebook.
  ; the module's package, will be the name of the module's group on the modules list page
  package = Nettuts+ Drupal Module Tutorial
  ; the Drupal core package
  core = 7.x
  ; the files array indicating which files are part of the module
  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.

Final Product


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.

Final Product

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:

  /**
   * Implements hook_node_view().
   *
   * Returns the renderable view of our nodes (pages or articles).
   * We want to moddify the code so that we add the like button
   * to our pages.
   */
  function facebook_node_view($node, $view_mode, $langcode)
  {
    $node->content['facebook'] = array(
      '#markup' => theme('facebook_add_like_button'),
    );
  }

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.

  /**
   * Implements hook_theme().
   *
   * Just to let Drupal know about our theme function.
   */
  function facebook_theme()
  {
    return array(
      'facebook_add_like_button' => array('variables' => NULL),
    );
  }

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:

  /**
   * Function to add the desired code to our page.
   */
  function theme_facebook_add_like_button()
  {
    $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>';
  
    return $output;
  }

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:

Final Product

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

  /**
   * Implements hook_block_info().
   *
   * Using this hook we declare to Drupal that our module
   * provides one block identified as facebook
   */
  function facebook_block_info()
  {
    $blocks['facebook'] = array(
      'info' => t('Facebook Recent Activity'),
    // leave the other properties of the block default
    );
  
    return $blocks;
  }

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:

  /**
   * Implements hook_block_view().
   *
   * Returns the renderable view of our block. It takes
   * the configured values of facebook recent activity
   * social plugin
   */
  function facebook_block_view($delta = '')
  {
    switch($delta) {
    case 'facebook' :
      $block['subject'] = t('Facebook recent activity');
      $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>';
    }
  
    return $block;
  }

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:

Final Product


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!

Tags: drupal
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://michael.theirwinfamily.net Michael

    Yah! It’s been a while since I’ve seen anything written about Drupal on here. Thanks for the tutorial! I’ve done quite a bit of module dev, but not much for Drupal 7. The hook_node_view would be very useful to have in D6. Might be time to look at updating!

    • Lukas

      In D6 you have hook_nodeapi with operation view

  • http://hy-studio.net Avril

    Very well explained tutorial :).

    I’ve created a very similar module for Facebook Recommend box. Created in such a way that you can set your width, height, url and color scheme in the Media administration panel.

    This is for Drupal 7 only. Don’t know if it’s worth to upload it to the community?

  • walter

    Great! Drupal post !!!
    More Drupal please…

  • Wasif

    Wow! great tut+.. it will be great and helpful if post more articles on drupal 7 module development… Thanx

  • http://www.brianbatesd.com Brian

    Awesome tutorial. Thanks! Nice to see a custom module implementation that is practical to follow.

  • http://www.d3.lt Zy

    Simple and practical tutorial.

  • http://www.vasudeesha.com Vasudeesha

    Nice Tutorial, Liked it..

  • Carlos

    Nice to see some Drupal 7 tutorials on Net Tuts.

  • w1sh

    I messed with Drupal for months but couldn’t get used to having to redo almost every module, form, etc, over and over.

    It’s cool for some things like Views (not even D7 is it?) for listing data, but if you ever want something custom, you might be better served just learning a real PHP framework like CodeIgniter or something.

    Dunno, Drupals FormAPI and advanced theming stuff just drove me up a wall. http://i.imgur.com/eEMjA.png

    • Abhijit

      If you are looking for love at first sight, then Drupal is perhaps not for you. However, if you can stick around and decide to go on trying, you sure will find that it’s the best thing that happened to you :)!

      • w1sh

        You mean with just 27 easy installments of 2-3 weeks, I too, can know how to list some data from a table in such a way that the markup produced is infinitely larger than the small amount of data I’m fetching?

        You mean, I could download and install 50 different modules to be able to display comments in a way where I can change the title of “Comments” to “Discussion”?!

        YOU MEAN, I COULD THEME A FRIGGIN’ DRUPAL FORM?!

        Hm…

        It sounds too good to be true. I think I’ll stick with real men frameworks like Django. ;)

  • http://www.pheromone.ca Laurent

    Finally some Drupal tutorials, the best CMS out there.

  • http://codingpad.maryspad.com mary

    Neat! Thanks for this tut.

  • http://www.rodneykeeling.com Rodney Keeling

    So, there’s a WordPress Tuts sub-domain now; can we get the same thing for Drupal? :D

    • Bruno Mateus

      Yeah! That’s the way to go!

    • Carlos

      +1 for Drupal

  • Dionisis

    Very practical and easy to follow tutorial!! Congruts!!!

    I guess we all really want more

    1. developing drupal 7 modules .
    2. creating custom themes

  • HassKappenMann

    THX 4 this tutorial! Great stuff! I like to see way more Drupal Tutorials on this Site, since you run one of the best Tutorial Sites on the web.

  • http://www.organic-web.net David L

    Dont suppose you could do this in wp too?

  • http://cristalz.com/ josephgiridhar

    Hi, I could really appropriate the site for providing such information which can lead to a end user with quality saving grace theme……….
    Sharing and caring is all about our world which leads helping each other in all aspect whether it can be through a information or by such a wonderful Wee themes……………

  • Bruno Mateus

    One thing, tough: please mention that all that code goes inside facebook.module file, I was scratching my head trying to understand in which files I should have placed it…

    The rest is marvellous. More, please please please!!!

  • Chris

    It’s extremely simple to use block/add and then add the fb code to node.tpl.php. Why is a custom module a better idea for this?

  • Pablo

    More Drupal please

  • tim

    more drupal!!!!

  • Iman

    Love your work.

  • kalabro

    Thank you very much!

    I’m php-developer with some experience on other CMS. But I want to learn other languages, frameworks, system to become really professional. When I were installing and trying Drupal it was difficult because I actually didn’t know what to do with it. I have known Drupal is very powerful and well-written CMS because many successful web companies and large web sites use of it.

    So the best way to start is to white some code. While I were creating simple module with this tutorial, a have used admin panel, configured other modules, worked with cache and theming, read source code of Drupal and other modules. And now I’m now very newbie drupaler and that’s cool!

    My experience of making first Drupal module (maybe it will be useful):
    1. Start using hooks is easy. Although understanding comes not immediately, but then you find hook like hook_form_alter() you see how cool it is.
    2. Start using database is extremely easy. I see that was not always, but in Drupal 7 you can uses things like hook_shema().
    3. For me, theming were not so easy but I could find all answers in drupal docs articles.
    4. To translate module you should use potx module. It finds all your t() messages and generates .po file. But my translation was installed only then I completely removed and reinstalled my module.

    I found many interesting and unknown futures while I were creating a module, but the first step have done!

    • kalabro

      Sorry for crazy English.
      And w1sh’s picture is very funny :)

  • Bart Wolthers

    I love the tut. It’s quite easy to follow… I do have one question though… when I enable the module, all it does is put the HTML code beneath the posts and in the sidebar… not the actual button or block…

    Any idea how this might be happening?

  • CaveSam

    Moooaaar Drupal please!!

  • http://www.108csr.com csr

    Drupal is the best….

  • http://www.tech-magneta.com Tech-Magneta

    Nice tutorial.
    Very Technical but can be followed.

    Thanx.

  • http://www.christoph-rumpel.com Christoph Rumpel

    Hi,

    maybe i am the only one, but i do not get where to put the code? Every time you show the code in your tut, i have to create a file and put in the facebook folder? Like “Implement hook_theme”… is this a new file?
    Maybe someone could help me with that.
    Thx greets

    • Ali

      you’ve to put all your functions in “facebook.module.php” page/file except module info

  • http://none.de as

    could someone share own code from this tut?
    1. i wrote from this tut code
    - working block info/view – not working facebook code
    - working alter form node – not working facebook code – html only print to screen

    2. i copy/paste from this tut and the same effect

    • Ali

      do you have any restriction on facebook at your testing server/machine?

  • Spencer

    Nice tutorial, thank you very much :) Please offer more tutorials on Drupal.

  • BZ

    I go to the XFBML tab on the Facebook developer page, and I have no clue what I’m supposed to copy/paste where. You just kind of skipped over that part.

  • BZ

    And why wouldn’t I just use the FB Like button module, then create a block and use the iFrame code Facebook generates? That works no problem and is so easy. Is there some kind of vulnerability when you do that?

  • http://www.technospiders.com jayendra

    Very helpful. Thanks to share this.

    • phpvn

      hi

      • phpvn

        hi all

      • phpvn

        hi every body

      • php

        LOL

  • GC

    I would like to know what to do with the THREE blocks of code I got from the XFBML tab of the Facebook page. The instructions on the FB page for each block are as follows:

    1. Include the JavaScript SDK on your page once, ideally right after the opening tag.

    (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = “//connect.facebook.net/en_US/all.js#xfbml=1″;
    fjs.parentNode.insertBefore(js, fjs);
    }(document, ‘script’, ‘facebook-jssdk’));

    2. Add an XML namespace to the tag of your document. This is necessary for XFBML to work in earlier versions of Internet Explorer.

    3. Place the code for your plugin wherever you want the plugin to appear on your page

    Where do I put each one of these blocks??

  • gc

    Sorry, those code blocks should have read:

    1. Include the JavaScript SDK on your page once, ideally right after the opening tag.

    <div id=”fb-root”></div>
    <script>(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = “//connect.facebook.net/en_US/all.js#xfbml=1″;
    fjs.parentNode.insertBefore(js, fjs);
    }(document, ‘script’, ‘facebook-jssdk’));</script>

    2. Add an XML namespace to the tag of your document. This is necessary for XFBML to work in earlier versions of Internet Explorer.

    <html xmlns:fb=”http://ogp.me/ns/fb#”>

    3. Place the code for your plugin wherever you want the plugin to appear on your page

    <fb:like href=”http://myDrupalSite.com” send=”true” width=”450″ show_faces=”true”></fb:like>

  • http://www.ravenblanco.com/guestbook/index.php View my web page

    Hi Dear, are you in fact visiting this site regularly, if so afterward you will without doubt get nice knowledge.

  • Yogeshfreelancer

    Very helpful … Thanks

  • cuong

    aa