9

The Flag module is still in development for Drupal 8, but it's working nice. However, I didn't find how to add a flag programmatically; the API documentation seems to speak of the Drupal 7 version.

How do I programmatically add a flag?

0

2 Answers 2

14

Here's how to flag or unflag an entity programmatically, using the Flag service.

$flag_id = 'bookmark';

$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

// Flag an entity with a specific flag.
$flag_service->flag($flag, $entity);

// Unflag an entity with a specific flag.
$flag_service->unflag($flag, $entity);

$flag->save();
3
  • In some case, i need to check if a content is not already flagged because double flagging produce an error. I will post an answer with an example. Dec 23, 2016 at 13:19
  • where to put above code
    – user52318
    Nov 19, 2018 at 11:33
  • Thanks, this save me a lot of time ;-) Nov 22, 2019 at 21:20
13

Flag for a certain user you will have to do :

$account = \Drupal::currentUser(); // or load a specific user
$flag_service = \Drupal::service('flag');

$flag = $flag_service->getFlagById('bookmark'); // replace by flag machine name

// check if already flagged
$flagging = $flag_service->getFlagging($flag, $media, $account);
if (!$flagging) {
  $flag_service->flag($flag, $media, $account);
}
else {
  $flag_service->unflag($flag, $media, $account);
}
2
  • What is $media?
    – Ali Nouman
    Sep 21, 2018 at 12:02
  • 1
    In my case it is a drupal Media object, but it could be any type of drupal Entity. Like a node for example.
    – romain ni
    Sep 21, 2018 at 15:04

Your Answer

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

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