in my custom module I have an event subscriber service for flag module. I used the tutorial here as a base for learning: Link to Tutorial
Here is my code:
namespace Drupal\MYMODULE\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\flag\Event\FlagEvents;
use Drupal\flag\Event\FlaggingEvent;
use Drupal\flag\Event\UnflaggingEvent;
use Drupal\user\UserInterface;
use Drupal\user\Entity\User;
class MYMODULEFlagSubscriber implements EventSubscriberInterface {
/**
* Do the logic when the upgrade flag is triggered to flag.
*/
public function onFlag(FlaggingEvent $event) {
$flagging = $event->getFlagging();
$flag = $flagging->getFlag();
$flag_machine_name = $flag->id();
if ($flag_machine_name === 'my_awesome_flag') {
$entity_nid = $flagging->getFlaggable()->id();
$user = User::load($entity_nid);
$user_is_active = $user->isActive();
$field_1 = $user->get('field_1')->value;
$field_2 = $user->get('field_2')->value;
$break_with_error = FALSE;
$upgrade_message = '';
$roles_to_ignore = [
'administrator_junior',
'team_sales',
'administrator',
];
if (!$user->hasRole('authenticated_level_2')) {
if (($user_is_active == TRUE) && ($field_1 == 1) && ($field_2 == 1)) {
foreach ($roles_to_ignore as $role_to_ignore) {
if ($user->hasRole($role_to_ignore)) {
$break_with_error = TRUE;
$upgrade_message = 'The User has a company role already and can not being upgraded as a Level 2 user.';
break;
}
}
}
else {
$break_with_error = TRUE;
$upgrade_message = 'The User can not being upgraded as a Level 2 User. Reasons: 2. The account is not activated yet, 3. The user has not yet checked field 2';
}
}
else {
$break_with_error = TRUE;
$upgrade_message = 'The User was upgraded as a Level 2 User already.';
}
switch ($break_with_error) {
case TRUE:
\Drupal::messenger()->addError($upgrade_message);
$flagging->unflag($flag_machine_name, $entity_nid);
return;
case FALSE:
$user->addRole('authenticated_level_2');
$user->save();
\Drupal::messenger()->addStatus('The User was upgraded as a Level 2 User sucessfully.');
return;
}
}
}
My Problem is
How can I unflag the flag again, when my logic checks settings and my variable $break_with_error becomes true?
$flagging->unflag($flag_machine_name, $entity_nid);
throws me an PHP error.
Update:
My intention was the following:
I use the flag here as a substitute for a link/button to trigger the "business logic" checks and to give the user a additional role with more privileges if the checks are passed.
In my opinion it's a easy way to quickly have a link/button in multiple variants (e.g. in a view or as a field in user account). Another advantage is, that other people (in my case sales team or other admins) see the business logic checks have performed already when the user entity is flagged. But in case the logic checks are failing, the user entity should unflagged again.
For other opportunities to have a "business logic trigger" I'm open and thankful of course. 🙂