[Drupal][Drupal 7] How to add text to a flag in a node when working with the Drupal Flag module

| | 2 min read

One of our Drupal clients wanted to us to enable members of her site to bookmark their favorite nodes. We went to work immediately as
we knew that this task could be accomplished by the Drupal Flag module. The flag module did enable us to implement that feature easily. Nevertheless we needed to add text near to the flag button/link on a specific node without affecting its display in a view. Read on to know how to dd text to a flag in a node when working with the Drupal Flag module.

We reviewed the documentation of the Drupal Flag module and it provided us with a mine of information. Here is what we found out.
To modify the display of the flags supplied by the Flag module we need two things.

  • 1. The Flag template file &
  • 2. Flag preprocess hook

The Flag template can be obtained from within the flag module.

sits/all/modules/flag/theme/flag.tpl.php

To make it work you need to copy and paste this template file into your theme file along with the rest of the template files. Remember to clear the cache after you do so so that Drupal recognizes the new template file. Editing the template file is sufficient but it is not a good coding practice and there is a better way with its corresponding hook. The hook in question is

hook_preprocess_flag()

I am listing out the code level implementation of the hook. It is a very simple hook. All the information you need is in the template variable - $vars. In the example below I have set the link text for a flagged as well as unflagged node.

/**
 * Implements hook_preprocess_flag()
 */
function MYTHEME_theme_preprocess_flag(&$vars) {
  // Adding text to the flag specific to a node
  if (arg(0) == 'node' && is_numeric(arg(1))) { 
    // We need to check if the node is already in the favorites list
    if ($vars['status'] == 'flagged') {
      $vars['link_text'] = "Click on the star to remove this node from your personal list of Favorites";
    }
    else {
      $vars['link_text'] = "Click on the star to add this node to your personal list of Favorites";
    }
  }
}

This system can be used for theming the flag and not limited to adding text. Reuse it as required by replacing the MYTHEME with your own theme.

Hope we were able to help you out if you were facing an issue with the flag module. If you have any questions regarding any Drupal specific issues then feel free to get in touch with us.