-1

I created a custom module to automatically flag new user accounts and updated accounts. When I create a new user or update an existing account, it is not automatically flagged and there is no error message in the log.

How do I flag new user accounts or updated accounts?

This is the code I am using in the custom module.

use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;

/**
 * Implements hook_user_update().
 */
function admin_task_notify_user_update(User $account) {
  $flag_id = 'moderate_user';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_admin = \Drupal\user\Entity\User::load(1);
  $flag_service->flag($flag, $account, $user_admin);
}
  • 1
    Comments are not for extended discussion; this conversation has been moved to chat. – Clive Sep 19 at 13:37
1
/**
 * Implements hook_form_alter()
 */
function admin_task_notify_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_form') { // check is user form
    $form['actions']['submit']['#submit'][] = 'admin_task_notify_flag_user'; // adds custom handler
  }
}

function admin_task_notify_flag_user(&$form, \Drupal\Core\Form\FormStateInterface $form_state) { // the custom handler
  $flag_id = 'moderate_user';
  $flag_service = \Drupal::service('flag');
  $flag = $flag_service->getFlagById($flag_id);
  $user_admin = \Drupal\user\Entity\User::load(1);
  $user_to_flag_uid = $form_state->getValue('uid');
  $user_to_flag = \Drupal\user\Entity\User::load($user_to_flag_uid);
  $flag_status = $flag_service->getFlagging($flag, $user_to_flag, $user_admin); // get flag status
  $is_admin = $user_to_flag->hasRole('administrator');
  if (!$flag_status && !$is_admin) { // if flag not TRUE, is FALSE, not flagged and user is not admin
    $flag_service->flag($flag, $user_to_flag, $user_admin);
  }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.