Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save gerzenstl/d1f3eb78e177b8fce024 to your computer and use it in GitHub Desktop.

Select an option

Save gerzenstl/d1f3eb78e177b8fce024 to your computer and use it in GitHub Desktop.
Drupal - Strips all leading and trailing white spaces on form fields.
/**
* Implements hook_form_alter().
*/
function my_module_form_alter(&$form, &$form_state, $form_id) {
/**
* We give a special treatment to all custom forms.
*/
if (substr($form_id, 0, 4) === 'my_module') {
array_unshift($form['#validate'],'my_module_trim_form_values');
}
}
/**
* Strips all leading and trailing whitespaces on form fields.
*/
function my_module_trim_form_values($form, &$form_state) {
// We left out of the trim treatment to any value that we know it's
// already ok (like Drupal specific values).
$white_list = array('form_id', 'form_token', 'form_build_id', 'op', 'submit');
foreach ($form_state['values'] as $k_val => $value) {
if (is_string($value) && !in_array($k_val, $white_list)) {
$form_state['values'][$k_val] = trim($value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment