I'm trying to alter some fields in the user profile form but I'm not sure why the form_id user-form is not working.

What I'm trying to achieve is to bring back the REQUIRED status of the password field which I turned off in user register form.

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, 
$form_id) { 
$userID = \Drupal::currentUser();
$userRole = $userID->getRoles();
if($userRole[1] == 'ROLETOCATCH'){
$form['account']['pass']['#required'] = FALSE;
$form['account']['mail']['#required'] = TRUE;
$form['account']['roles']['campaign_manager']['#default_value'] =  TRUE;
$form['account']['notify']['#default_value'] = TRUE;

function MYMODULE_form_user_form_form_alter(&$form, &$form_state, 
$form_id) {
  • form ID for user edit form: user_profile_form
    – Mahesh V
    Feb 2 '18 at 7:02
  • Still not working, I've tried this before. Feb 2 '18 at 7:27
  • In D8, the 'user_profile_form' is now call 'user_form'. Then to use it directly with the hook_form_alter(), you must use 'MYMODULE_form_user_form_alter'. On your code you have MYMODULE_form_user_form_form_alter.
    – TytooF
    Jun 12 '20 at 9:23

To override the user form (when editing user profile) you can use hook_form_alter with user_form id.

On the following example code the current_pass is required so anyone making changes will need to enter it. Also we assume that any administrator would not be forced to enter the password.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) { 
  $user = \Drupal::currentUser()->getRoles();
  //admin's probably should not be forced to enter password 
  if(!in_array("administrator", $user) && $form_id == 'user_form') {
    //$form['account']['pass']['#required'] = TRUE;    
    $form['account']['current_pass']['#required'] = TRUE;    

The user register form can be overriden with either one

function MODULENAME_form_user_register_form_alter(&$form, &$form_state, $form_id) { 

function MODULENAME_form_alter(&$form, &$form_state, $form_id) { 
  if($form_id == "user_register_form"){

The module has to be enabled and/or the cache should be rebuild for the system to see those functions

  • the user_register_form_alter is working on my side. what I'm looking for is the hook alter the for editing user profile. Feb 5 '18 at 3:22
  • revised the answer please check
    – GiorgosK
    Feb 5 '18 at 4:53

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.