Standalone - remove role from users on deletion
authorWilliam Mortada <williammortada@thirdsectordesign.org>
Sat, 2 Dec 2023 19:01:32 +0000 (19:01 +0000)
committerWilliam Mortada <williammortada@thirdsectordesign.org>
Sun, 3 Dec 2023 11:28:12 +0000 (11:28 +0000)
ext/standaloneusers/CRM/Standaloneusers/BAO/Role.php

index 45a85eafe8948c7efe7f50730b69c3af55efa1eb..de1bf5ba18011bd5c30fba9f34c136caaf09dcef 100644 (file)
@@ -10,6 +10,21 @@ class CRM_Standaloneusers_BAO_Role extends CRM_Standaloneusers_DAO_Role implemen
    * @param \Civi\Core\Event\PostEvent $event
    */
   public static function self_hook_civicrm_post(\Civi\Core\Event\PostEvent $event) {
+    // Remove role from users on deletion
+    if ($event->action === 'delete') {
+      $users = \Civi\Api4\User::get(FALSE)
+        ->addSelect('id', 'roles')
+        ->addWhere('roles', 'CONTAINS', $event->id)
+        ->execute();
+      foreach ($users as $user) {
+        $roles = array_diff($user['roles'], [$event->id]);
+        \Civi\Api4\User::update(FALSE)
+          ->addValue('roles', $roles)
+          ->addWhere('id', '=', $user['id'])
+          ->execute();
+      }
+    }
+
     // Reset cache
     Civi::cache('metadata')->clear();
   }