You are here

public function FlagService::unflag in Flag 8.4

Unflags the given entity for the given flag.

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

Parameters

\Drupal\flag\FlagInterface $flag: The flag being unflagged.

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

\Drupal\Core\Session\AccountInterface $account: (optional) The account of the user that created the flagging. Defaults to the current user.

string $session_id: (optional) If $account is anonymous then the $session_id MUST be used to identify a user uniquely. If $account and $session_id are NULL and the current user is anonymous then the current session_id will be used.

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 not currently flagged with this flag by the user.
  • The user is anonymous but not uniquely identified by session_id.

Overrides FlagServiceInterface::unflag

File

src/FlagService.php, line 273

Class

FlagService
Flag service.

Namespace

Drupal\flag

Code

public function unflag(FlagInterface $flag, EntityInterface $entity, AccountInterface $account = NULL, $session_id = NULL) {
  $bundles = $flag
    ->getBundles();
  $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.');
  }
  $flagging = $this
    ->getFlagging($flag, $entity, $account, $session_id);

  // Check whether there is an existing flagging for the combination of flag,
  // entity, and user.
  if (!$flagging) {
    throw new \LogicException('The entity is not flagged by the user.');
  }
  $flagging
    ->delete();
}