/** * Performs a flagging when called via a route. * * @param \Drupal\flag\FlagInterface $flag * The flag entity. * @param int $entity_id * The flaggable ID. * * @return AjaxResponse * The response object. * * @see \Drupal\flag\Plugin\ActionLink\AJAXactionLink */ public function flag(FlagInterface $flag, $entity_id) { $flag_id = $flag->id(); $account = $this->currentUser(); $flagging = $this->entityTypeManager()->getStorage('flagging')->create([ 'flag_id' => $flag->id(), 'entity_type' => $flag->getFlaggableEntityTypeId(), 'entity_id' => $entity_id, 'uid' => $account->id(), ]); return $this->getForm($flagging, 'add'); }
/** * {@inheritdoc} */ public function unflag(FlagInterface $flag, EntityInterface $entity, AccountInterface $account = NULL) { $bundles = $flag->getBundles(); // 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); // 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.'); } $this->eventDispatcher->dispatch(FlagEvents::ENTITY_UNFLAGGED, new FlaggingEvent($flag, $entity)); $flagging->delete(); }
/** * Gets the flag type label for the given flag. * * @param \Drupal\flag\FlagInterface $flag * The flag entity. * * @return array * A render array of the flag type label. */ protected function getFlagType(FlagInterface $flag) { // Get the flaggable entity type definition. $flaggable_entity_type = \Drupal::entityTypeManager() ->getDefinition($flag->getFlaggableEntityTypeId()); return [ '#markup' => $flaggable_entity_type->getLabel(), ]; }
/** * {@inheritdoc} */ public function getFlagFlaggingCount(FlagInterface $flag) { $flag_id = $flag->id(); $entity_type = $flag->getFlaggableEntityTypeId(); // We check to see if the flag count is already in the cache, // if it's not, run the query. if (!isset($this->flagCounts[$flag_id][$entity_type])) { $result = $this->connection->select('flagging', 'f') ->fields('f', ['flag_id']) ->condition('flag_id', $flag_id) ->condition('entity_type', $entity_type) ->countQuery() ->execute() ->fetchField(); $this->flagCounts[$flag_id][$entity_type] = $result; } return $this->flagCounts[$flag_id][$entity_type]; }