The obligatory nature of fields

17/03/2016

In this snippet we will mark the obligatory fields present as non-obligatory, and it will be under the condition that the user actually has the role of administrator.  With this snippet, we can also do the reverse operation.  For example, if no fields are marked as obligatory, we can write a condition to turn them into obligatory fields.

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_profile_form':
      global $user;
      if (array_intersect(array('adminRol1', 'adminRol2'), $user->roles)) {
        $form['#after_build'][] = 'callback_set_fields_not_required';
      }
      break;
  }
}

/**
 * Mark all the fields in a form (which are required) as not required.
 *
 * Callback for MY_MODULE_form_alter().
 *
 * @param $element
 *   Form to be processed.
 *
 * @return mixed
 *   Form with fields not required.
 *
 * @ingroup callbacks
 */
function callback_set_fields_not_required($element) {
  foreach (element_children($element) as $name) {
    $element[$name][LANGUAGE_NONE]['#required'] = FALSE;
    $element[$name][LANGUAGE_NONE][0]['#required'] = FALSE;
    $element[$name][LANGUAGE_NONE][0]['value']['#required'] = FALSE;
  }

  return $element;
}