Add a user role depending on the value of a user field

Public

Get raw version
php
  1. /**
  2.  * Implements hook_form_alter for user_profile_form
  3.  */
  4. function MYMODULE_form_user_profile_form_alter(&$form, &$form_state, $account, $category = 'account') {
  5. // Add an additional submit handler for the user_profile_form
  6. array_unshift($form['#submit'], 'MYMODULE_user_profile_form_submit');
  7. }
  8.  
  9. /**
  10.  * Additional submit handler for the user_profile_form
  11.  */
  12. function MYMODULE_user_profile_form_submit($form, &$form_state) {
  13. $values = &$form_state['values'];
  14.  
  15. if (!empty($values['field_user_type'])) {
  16. $tid = $values['field_user_type']['und'][0]['tid'];
  17. $term = taxonomy_term_load($tid);
  18.  
  19. $roles = user_roles();
  20.  
  21. if ($term->name == 'Regular employee') {
  22. // add role ...
  23. drupal_set_message(t('Set the role %name', array('%name' => $roles[$rid])));
  24. $values['roles'][$rid] = TRUE;
  25. }
  26. else {
  27. // remove role ..
  28. drupal_set_message(t('Removed the role %name', array('%name' => $roles[$rid])));
  29. $values['roles'][$rid] = FALSE;
  30. }
  31. }
  32. }