Warning: key() expects parameter 1 to be array, null given in Drupal\user\AccountForm->buildEntity() (line 312 of core/modules/user/src/AccountForm.php).

Dealing with Drupal's Unpredictable User Roles

When Unset() Isn't the Answer

When working with Drupal, you might encounter an error that leaves you scratching your head. The issue arises when trying to modify user roles in a way that Drupal didn't anticipate. In such cases, using the unset() function won't get you out of trouble.

Solution, instead of using unset(), do:

 $form['account']['roles']['#access'] = FALSE; 
This unusual solution will help you circumvent the error and proceed with your user role modifications.

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!