function flag_form_save in Flag 8.4
Performs flagging/unflagging for the entity edit form.
Parameters
\Drupal\Core\Entity\EntityInterface $entity: The entity being saved.
$values: The flag entity form values.
See also
1 call to flag_form_save()
- flag_form_submit in ./
flag.module - Form submission handler for the flag module.
File
- ./
flag.module, line 214 - The Flag module.
Code
function flag_form_save(EntityInterface $entity, $values) {
$flag_service = \Drupal::service('flag');
$account = \Drupal::currentUser();
// For existing entities, get any existing flaggings per flag.
$flagging_ids = [];
if (!$entity
->isNew()) {
$flaggings = $flag_service
->getAllEntityFlaggings($entity, $account);
$flagging_ids = array_map(function ($flagging) {
return $flagging
->getFlagId();
}, $flaggings);
}
// Load all the flags for the entity.
$flags = $flag_service
->getAllFlags($entity
->getEntityTypeId(), $entity
->bundle());
/** @var FlagInterface $flag */
foreach ($flags as $flag) {
// Get the flag_id from the Flag.
$flag_id = $flag
->id();
// If the flag_id is not part of the form values, no need to do anything.
if (!isset($values[$flag_id])) {
continue;
}
// Get the form flag value.
$value = $values[$flag_id];
// Determine if the flagging exists.
$flagging_exists = in_array($flag_id, $flagging_ids);
// If the flag is checked in the form, and the flagging doesn't exist...
if ($value && !$flagging_exists) {
// ...flag the entity.
$flag_service
->flag($flag, $entity);
}
// If the flag is not checked in the form, and the flagging exists..
if (!$value && $flagging_exists) {
// ...unflag the entity.
$flag_service
->unflag($flag, $entity);
}
}
}