From 77f68d88d633394c2ec17a5bbc77361620aa38bd Mon Sep 17 00:00:00 2001 From: Matthew Wire Date: Thu, 6 Feb 2020 22:40:48 +0000 Subject: [PATCH] Add the HTML5 style required attribute to quickform elements --- CRM/Core/Form.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CRM/Core/Form.php b/CRM/Core/Form.php index 416085c733..77ec3d2fae 100644 --- a/CRM/Core/Form.php +++ b/CRM/Core/Form.php @@ -419,6 +419,7 @@ class CRM_Core_Form extends HTML_QuickForm_Page { unset($extra['option_context']); } + $this->addRequiredAttribute($required, $extra); $element = $this->addElement($type, $name, CRM_Utils_String::purifyHTML($label), $attributes, $extra); if (HTML_QuickForm::isError($element)) { CRM_Core_Error::fatal(HTML_QuickForm::errorMessage($element)); @@ -1145,6 +1146,20 @@ class CRM_Core_Form extends HTML_QuickForm_Page { return self::$_template->get_template_vars($name); } + /** + * jQuery validate prefers to see a validation rule as a class (eg. "required"). + * We can't add a class at the quickform level but jQuery validate also works with HTML5: + * HTML5 validation requires a separate attribute "required". + * + * @param $required + * @param $attributes + */ + private function addRequiredAttribute($required, $attributes) { + // Ideally we do this by adding "required" as a class on the radio but we can't + // But adding the attribute "required" directly to the element also works. + $required ? $attributes['required'] = 1 : NULL; + } + /** * @param string $name * @param $title @@ -1162,6 +1177,8 @@ class CRM_Core_Form extends HTML_QuickForm_Page { $allowClear = !empty($attributes['allowClear']); unset($attributes['allowClear']); $attributes['id_suffix'] = $name; + // For jquery validate we need to flag the actual radio as required. + $this->addRequiredAttribute($required, $attributes); foreach ($values as $key => $var) { $optAttributes = $attributes; if (!empty($optionAttributes[$key])) { -- 2.25.1