Skip to content

Instantly share code, notes, and snippets.

@chasingmaxwell
Last active September 19, 2017 08:28
Show Gist options
  • Save chasingmaxwell/7324854 to your computer and use it in GitHub Desktop.
Save chasingmaxwell/7324854 to your computer and use it in GitHub Desktop.
Drupal 7: Add HTML5 required attribute to all form elements with '#required' => TRUE.
<?php
/**
* This goes in YOUR_MODULE.module file.
*/
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
// Always add the html5 required attribute for required elements.
_YOUR_MODULE_html5_required($form);
}
function _YOUR_MODULE_html5_required($element) {
if (is_array($element)) {
if ((isset($element['#type']) && $element['#type'] !== 'checkboxes') && isset($element['#required']) && $element['#required']) {
$element['#attributes']['required'] = '';
}
else {
foreach (element_get_visible_children($element) as $key) {
_YOUR_MODULE_html5_required($element[$key]);
}
}
}
}
@NL9
Copy link

NL9 commented Sep 19, 2017

function _YOUR_MODULE_html5_required($element) should be function _YOUR_MODULE_html5_required(&$element) .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment