Community Documentation

The Flag 3.x API (PHP)

Last updated September 14, 2012. Created by joachim on August 23, 2012.
Edited by IceCreamYou2. Log in to edit this page.

[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') or die('no "bookmarks" flag defined');

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


$flag = flag_get_flag('idiots') or die('no "idiots" flag defined');

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


$flag = flag_get_flag('idols') or die('no "idols" flag defined');

// 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->is_flagged($node->uid, $GLOBAL['user']->uid)) {
  print
"This author venerates you!";
}

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

The examples above makes PHP die() if the flag doesn't exist. A different style is to add $flag && to the conditional:

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

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

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') or die('no "votes" 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') or die('no "votes" flag');

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

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') or die('no "bookmarks" flag defined');

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

// Unflag node #456:
$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_flag(), and to the removal of a flag from a piece of content by implementing hook_flag_unflag().

<?php
mymodule_flag_flag
($flag, $content_id, $account, $flagging) {
 
// Do something in response to the flagging.
}

mymodule_flag_unflag($flag, $content_id, $account, $flagging) {
 
// Do something in response to the unflagging.
}
?>

Flag module actually implements its own hook in the flag_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_entity_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 : $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:

<?php
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.:

<?php
...
$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.

To avoid conflicts with other modules that might provide a flag with the same name, developers should prefix the names of default flags with their module's name.

<?php
function mymodule_flag_default_flags() {
 
$flags = array();
 
$flags[] = array(
   
'content_type' => 'node',
   
'name' => 'mymodule_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;
}
?>

About this page

Drupal version
Drupal 7.x
Audience
Programmers, Site builders

Structure Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.
nobody click here