[Drupal] How to avoid profile validation on user delete?

| | 2 min read

One of our clients had a problem that when they try to delete users who have signed up via mobile app they get an error saying they must enter a street address for the user before the account can be deleted. This was because users who sign up via the mobile app were not asked for their street address, but on the Drupal site the street address is a required field when a user signs up.

We wanted to fix this issue in such a way that we should be able to delete accounts that do not have street addresses, keeping the street address to be a required field when users sign up via the Drupal site. So we began thinking that what would be the best way to skip the validation of a user profile and its fields while deleting a user account? The solution that we got was pretty simple. Here is how we achieved it.

We can do it in a few easy steps:

1. Hide the existing 'Cancel account' button using CSS

#user-profile-form #edit-cancel {
  display: none;
}

2. Add a custom button which points to the user-cancel page directly.

In your custom module, include the following code inside your form alter function

/**
 * Impementation of hook_form_alter().
 */
function custom_user_form_alter(&$form, &$form_state, $form_id) {

  // For deleting user profile without validating the form.
  if ($form_id == 'user_profile_form') { 
    $form['cancel'] = array(
    '#type' => 'button',
    '#value' => t('Cancel account'),
    '#weight' => 20,
    '#attributes' => array('onClick' => 'location.replace("cancel?destination=admin/config/custom/users-list"); return false;'),
    );
}

This code will eliminate all form validation but still asks for usual confirmation form before deleting the user profile.

Enjoy it!