You are here

public function FlagService::flag in Flag 8.4

Flags the given entity given the flag and entity objects.

To programatically create a flagging between a flag and an article:

$flag_service = \Drupal::service('flag');
$flag = $flag_service
  ->getFlagById('bookmark');
$node = Node::load($node_id);
$flag_service
  ->flag($flag, $node);

Parameters

\Drupal\flag\FlagInterface $flag: The flag entity.

\Drupal\Core\Entity\EntityInterface $entity: The entity to flag.

\Drupal\Core\Session\AccountInterface $account: (optional) The account of the user flagging the entity. If not given, the current user is used.

string $session_id: (optional) The session ID. If $account is NULL and the current user is anonymous, then this can also be omitted to use the current session. to identify an anonymous user.

Return value

\Drupal\flag\FlagInterface|null The flagging.

Throws

\LogicException An exception is thrown if the given flag, entity, and account are not compatible in some way:

  • The flag applies to a different entity type from the given entity.
  • The flag does not apply to the entity's bundle.
  • The entity is already flagged with this flag by the user.
  • The user is anonymous but not uniquely identified by session_id.

Overrides FlagServiceInterface::flag

File

src/FlagService.php, line 234

Class

FlagService
Flag service.

Namespace

Drupal\flag

Code

public function flag(FlagInterface $flag, EntityInterface $entity, AccountInterface $account = NULL, $session_id = NULL) {
  $bundles = $flag
    ->getBundles();
  $this
    ->ensureSession();
  $this
    ->populateFlaggerDefaults($account, $session_id);

  // Check the entity type corresponds to the flag type.
  if ($flag
    ->getFlaggableEntityTypeId() != $entity
    ->getEntityTypeId()) {
    throw new \LogicException('The flag does not apply to entities of this type.');
  }

  // Check the bundle is allowed by the flag.
  if (!empty($bundles) && !in_array($entity
    ->bundle(), $bundles)) {
    throw new \LogicException('The flag does not apply to the bundle of the entity.');
  }

  // Check whether there is an existing flagging for the combination of flag,
  // entity, and user.
  if ($flag
    ->isFlagged($entity, $account, $session_id)) {
    throw new \LogicException('The user has already flagged the entity with the flag.');
  }
  $flagging = $this->entityTypeManager
    ->getStorage('flagging')
    ->create([
    'uid' => $account
      ->id(),
    'session_id' => $session_id,
    'flag_id' => $flag
      ->id(),
    'entity_id' => $entity
      ->id(),
    'entity_type' => $entity
      ->getEntityTypeId(),
    'global' => $flag
      ->isGlobal(),
  ]);
  $flagging
    ->save();
  return $flagging;
}