Browse Source

Merge branch '5.x' into 5.next

Mark Story 1 year ago
parent
commit
f4247e7f40
2 changed files with 28 additions and 1 deletions
  1. 5 1
      src/View/Helper/FormHelper.php
  2. 23 0
      tests/TestCase/View/Helper/FormHelperTest.php

+ 5 - 1
src/View/Helper/FormHelper.php

@@ -1425,9 +1425,13 @@ class FormHelper extends Helper
             $options['templateVars']['customValidityMessage'] = $message;
 
             if ($this->getConfig('autoSetCustomValidity')) {
+                $condition = 'this.value';
+                if ($options['type'] === 'checkbox') {
+                    $condition = 'this.checked';
+                }
                 $options['data-validity-message'] = $message;
                 $options['oninvalid'] = "this.setCustomValidity(''); "
-                    . 'if (!this.value) this.setCustomValidity(this.dataset.validityMessage)';
+                    . "if (!{$condition}) this.setCustomValidity(this.dataset.validityMessage)";
                 $options['oninput'] = "this.setCustomValidity('')";
             }
         }

+ 23 - 0
tests/TestCase/View/Helper/FormHelperTest.php

@@ -7828,6 +7828,7 @@ class FormHelperTest extends TestCase
             ->notEmptyString('email', 'Custom error message')
             ->requirePresence('password')
             ->alphaNumeric('password')
+            ->requirePresence('accept_tos')
             ->notBlank('phone');
 
         $table = $this->getTableLocator()->get('Contacts', [
@@ -7894,6 +7895,28 @@ class FormHelperTest extends TestCase
             ],
         ];
         $this->assertHtml($expected, $result);
+
+        $result = $this->Form->control('accept_tos', ['type' => 'checkbox']);
+        $expected = [
+            ['input' => ['type' => 'hidden', 'name' => 'accept_tos', 'value' => '0']],
+            'label' => ['for' => 'accept-tos'],
+            [
+                'input' => [
+                    'aria-required' => 'true',
+                    'required' => 'required',
+                    'type' => 'checkbox',
+                    'name' => 'accept_tos',
+                    'id' => 'accept-tos',
+                    'value' => '1',
+                    'data-validity-message' => 'This field cannot be left empty',
+                    'oninput' => 'this.setCustomValidity('')',
+                    'oninvalid' => 'this.setCustomValidity(''); if (!this.checked) this.setCustomValidity(this.dataset.validityMessage)',
+                ],
+            ],
+            'Accept Tos',
+            '/label',
+        ];
+        $this->assertHtml($expected, $result);
     }
 
     /**