0

Is it possible to get the following raw, low level data from the Flag Module and/or it's services?

  • Flagging count as integer
  • URL to flag/unflag as a string
  • Current user's flagging status as boolean

I already know that I can do this:

$flag_link = \Drupal::service('flag.link_builder')->build('node',$nid,'bookmark');

But it will output the full blown markup with Ajax and everything.

I've done this:

$flag_service = Drupal::service('flag.count');
$counts = $flag_service->getEntityFlagCounts($node);

But I can't actually figure out what exactly $counts contains, I definitely can't output it as an integer on my template, I get an error.

1 Answer 1

0

To get the total flagging count:

$count_service = \Drupal::service('flag.count');
$flag_counts = $count_service->getEntityFlagCounts($node);
$count = $flag_counts['my_flag'];

To get the current user's flagging status:

$flag_service = \Drupal::service('flag');
$my_flag = $flag_service->getFlagById('my_flag');
$user = \Drupal::currentUser();
$is_flagged= $my_flag->isFlagged($node,$user);

to toggle the flagging status:

if(!$is_flagged){
    $flag_service->flag($my_flag , $node);
}

or

if($is_flagged){
    $flag_service->unflag($my_flag , $node);
}

Best to wrap all of this into an if clause

if( $user->isAuthenticated() ){ ... }

It's probably easiest to just build my own URL / route to take care of the toggling to fit my needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.