Drupal – Setting multiple flags using hook_flag_flag

Drupal has a great flag module that is able to flag pieces of content. Sometimes you want one flag to be able to set other flags as well. Drupal provides a hook for whenever an item is flagged. This hook can’t easily be used to flag an item beacuse each time you attempt to flag another item the hook gets called again and again until PHP is out of memory — it’s pretty much infinite recursion. There is a way to fix this and it goes like this:

[php]

< ?php static $ran = FALSE; if($ran === FALSE){ $ran = TRUE; if($flag->name == ‘flag1’){
$newflag = flag_get_flag(‘flag2’, $node_id);
$newflag->flag(‘flag’, $node_id, $account);

$newflag2 = flag_get_flag(‘flag3’, $node_id);
$newflag2->flag(‘flag’, $node_id, $account);

}else if($flag->name == ‘flag2’){
$newflag = flag_get_flag(‘flag1’, $node_id);
$newflag->flag(‘flag’, $node_id, $account);

$newflag2 = flag_get_flag(‘flag3’, $node_id);
$newflag2->flag(‘flag’, $node_id, $account);

}else if($flag->name == ‘flag3’){
$newflag = flag_get_flag(‘flag1’, $node_id);
$newflag->flag(‘flag’, $node_id, $account);

$newflag2 = flag_get_flag(‘flag2’, $node_id);
$newflag2->flag(‘flag’, $node_id, $account);
}

}

?>

[/php]

There are three flags, and when each of them gets set, the other two flags are set. This works because the static variable above tells Drupal that this function has already been run in the current script execution which stops the recusion. This then works as expected.

Published on: 27 June 2014
Posted by: Sami K.