The Flag 2.x API (PHP)

Last updated on
30 April 2025

[This page contains some random notes. When more material is gathered, it will be revised.]

Contents:

First and foremost

Flag provides some API functions. At some point we switched to use object oriented programming (OOP). Some functions don't have equivalent methods (yet?).

To work with a flag you first need to get your hands on a "flag handler":

$flag = flag_get_flag('bookmarks');

The parameter to flag_get_flag() is the machine-name of the flag. If no such flag exists, NULL will be returned.

Discovering whether a piece of content is flagged

Use the is_flagged() method to find out if an item is flagged.

This can be very useful in 'node.tpl.php', when you want to theme flagged nodes differently than non-flagged ones.

Examples:

<?php
$flag = flag_get_flag('bookmarks');

if ($flag && $flag->is_flagged($node->nid)) {
  print "This node is bookmarked!";
}


$flag = flag_get_flag('idiots');

if ($flag && $flag->is_flagged($node->nid)) {
  print "The author of this node isn't very smart!";
}


$flag = flag_get_flag('idols');

// Note the optional second parameter to is_flagged(), which allows
// us to ask if an item is flagged on behalf of a certain user. If this
// parameter isn't provided, the check is made against the current user.
//
// If the flag is "global", this second parameter is ignored.
//
if ($flag && $flag->is_flagged($node->uid, $GLOBAL['user']->uid)) {
  print "This author venerates you!";
}

// flag::is_flagged() uses a caching mechanism so it's efficient.
?>

You use flag_create_link() for this. See the separate page, Placing a flag link on a page.

Getting the number of times an item is flagged

Whenever an item is flagged, or unflagged, a counter field is updated. To read this counter, use the get_count() method:

<?php
$flag = flag_get_flag('votes');

if ($flag) {
  print "The number of people who voted for this proposal:";
  print $flag->get_count($node->nid);
}
?>

A different approach is to use tokens. This module provides a count token for each flag, and you can use it in email messages, for example, and in every place that accepts tokens:

<?php
Hello, [node-author].
Your post has been bookmarked [flag-bookmarks-count] times.
?>

A different method, get_user_count(), is used for counting the items a user has flagged. This method is less efficient than get_count() because an SQL COUNT query is issued.

$flag = flag_get_flag('votes');

// We assume an $account variable exists in this template.

if ($flag) {
  print format_plural($flag->get_user_count($account->uid),
    'This user has participated in 1 voting.',
    'This user has participated in @count votings.');
}

Flagging or Unflagging an item

You use the $flag->flag() method to either flag or unflag an item. Example:

<?php
$flag = flag_get_flag('bookmarks');

// Flag node #456:
if ($flag) {
  $flag->flag('flag', 456); 
}

// Unflag node #456:
if ($flag) {
  $flag->flag('unflag', 456); 
}
?>

The signature of this $this->flag() method is:

<?php
function flag($action, $content_id, $account = NULL, $skip_permission_check = FALSE)
?>

A complete and up-to-date documentation of it is in the Doxygen. But, in short: $action is the action you want to carry out; either 'flag' or 'unflag'. $content_id is the identifier of the item. $account is the user on whose behalf you want to carry out the action (This parameter is only meaningful when using a non-global flag). Please note that this is the user object, not the uid. The last parameter of this method is important when flagging/unflagging a node as an non-privileged user, such as in a hook_cron() implementation where the server runs as anonymous and permission checks would fail silently without $skip_permission_check = TRUE.

This method returns FALSE if some error occured (e.g., the user has no permission to use this flag; flag isn't applicable to the item; etc.). Note that it isn't an error to flag an item that is already flagged (in this case the method will do nothing, but it will not return FALSE).

Responding to a flagging

Any module may react to a piece of content being flagged by implementing hook_flag().

mymodule_flag($action, $flag, $content_id, $account) {
  if ($action == 'flag') { // Or $action == 'unflag'.
    // Do something in response to the flagging.
  }

  if ($flag->name == 'yourflagname') {
    //Do something if the flag is "yourflagname". Example "Bookmark".
  }

}

Flag module actually implements its own hook in the flag_flag() function in flag.module. You might use it for reference when creating your own version.

Creating a Flag in the Database

To create a node flag in the database, create a flag from the flag_flag class, modify the defaults, then save with the $flag->save() method. Note that you can also create

  $flag = flag_flag::factory_by_content_type('node');

  // Absolutely required, will break your site if not added properties.
  $flag->name = 'my_flag_name';
  $flag->title = 'My Title';

  // Properties required by the UI.
  $flag->roles = array(2); // An array of role IDs. 2 is for "authenticated users".
  //in D6 and D7 : $flag->roles = array( 'flag' => array('2'), 'unflag' => array('2') );
  $flag->types = array('story', 'page'); // An array of node types.
  $flag->flag_short = 'Flag this';
  $flag->unflag_short = 'Unflag this';

  // Optional properties, defaults are defined for these (and more).
  // Use a print_r() or dsm() to see all the available flag properties.
  $flag->global = TRUE;
  $flag->flag_long = '';
  $flag->flag_message = '';
  $flag->show_on_form = TRUE;
  $flag->show_on_node = TRUE;
  $flag->show_on_teaser = TRUE;
  $flag->link_type = 'toggle'; // For JS link. Other options: 'normal' and 'confirm'.

  // Save the flag.
  $flag->save(); 

Can do something similar for user flags (here's an example in an update function) - and can also use a values array instead of setting attributes:

function mymodule_update_6100() {
  $ret = array();
  $flag = flag_flag::factory_by_entity_type('user');
  // Unique, machine-readable name.
  $flag->name = 'unverified_user';
  $values = array(
    'flag_short' => 'mark as unverified',
    'flag_long' => '',
    'flag_message' => '',
    'flag_confirmation' => '',
    'unflag_short' => 'mark as verified',
    'unflag_long' => '',
    'unflag_message' => '',
    'unflag_confirmation' => '',
    'link_type' => 'normal',
    'show_on_profile' => 1,
    'global' => 1,
    // A user flag doesn't support node types.
    'types' => array(),
    'roles' => array(2),
    'title' => 'Unverified user',
  );
  $flag->form_input($values);
  $flag->save();
  $flag->enable();
  $ret[] = array('success' => !empty($flag->fid), 'query' => 'Created user flag ' . $flag->name);
  return $ret;
}

Note: If you create a flag in an update hook or in hook_install() and want to immediately use it you must first call flag_get_flags() to reload Flag's static cache of flags, otherwise flag_get_flag() won't find your new one. E.g.:

...
$flag->save();
flag_get_flags(NULL, NULL, NULL, TRUE);  // Force the new flag to be loaded
...

Creating a Module-Based Default Flag

Flags can be included in modules by implementing hook_flag_default_flags(). By defining a flag in code, the developer can "lock" certain properties of a flag and ensure that a flag is available for the module to use. Any "locked" properties will not be shown on the flag configuration form.

function mymodule_flag_default_flags() {
  $flags = array();
  $flags[] = array(
    'content_type' => 'node',
    'name' => 'starred',
    'title' => 'Starred',
    'roles' => array('2'),
    'global' => FALSE,
    'types' => array('story', 'blog'),
    'flag_short' => 'Star',
    'flag_long' => 'Add this your starred list',
    'flag_message' => 'Added to your starred list.',
    'unflag_short' => 'Unstar',
    'unflag_long' => 'Remove this issue from your starred list',
    'unflag_message' => 'Removed from your starred list.',
    'show_on_page' => TRUE,
    'show_on_teaser' => TRUE,
    'show_on_form' => FALSE,
    'status' => FALSE,
    'locked' => array('show_on_teaser', 'name', 'types', 'roles', 'global'),
  );
  return $flags;
}

How to Delete a Flag

If you create a module which creates a Flag you would also want to be able to delete that flag when the Module is Uninstalled. The code below will allow you to delete a flag:

<?php
//First you have to load the flag that needs to be deleted:
$flag = flag_get_flag('bookmarks');

//If the flag does not exist then NULL is returned
if($flag) {
     $flag->delete(); // If the flag exist then delete the flag
}
?>

Help improve this page

Page status: Not set

You can: