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?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityThe 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?
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();
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);
}