Browse Source

Simplify code.

Max length set in options should take highest precedence, followed by validator and lastly schema.
ADmad 7 years ago
parent
commit
a3a3141109

+ 1 - 11
src/View/Form/ArrayContext.php

@@ -243,17 +243,7 @@ class ArrayContext implements ContextInterface
             return null;
         }
 
-        $fieldSchema = Hash::get($this->_context['schema'], $field);
-
-        if (!$fieldSchema) {
-            return null;
-        }
-
-        if (is_array($fieldSchema)) {
-            return Hash::get($fieldSchema, 'length');
-        }
-
-        return null;
+        return Hash::get($this->_context['schema'], "$field.length");
     }
 
     /**

+ 8 - 12
src/View/Helper/FormHelper.php

@@ -1503,23 +1503,19 @@ class FormHelper extends Helper
         }
 
         $typesWithMaxLength = ['text', 'textarea', 'email', 'tel', 'url', 'search'];
-        if (in_array($options['type'], $typesWithMaxLength)) {
-
+        if (!array_key_exists('maxlength', $options)
+            && in_array($options['type'], $typesWithMaxLength)
+        ) {
+            $maxLength = null;
             if (method_exists($context, 'getMaxLength')) {
                 $maxLength = $context->getMaxLength($fieldName);
             }
 
-            if (!empty($fieldDef['length']) && isset($maxLength)) {
-                $fieldDef['length'] = min($fieldDef['length'], $maxLength);
-            } elseif (isset($maxLength)) {
-                $fieldDef['length'] = $maxLength;
-            }
-            if (!empty($options['maxlength'])) {
-                $fieldDef['length'] = min($fieldDef['length'], $options['maxlength']);
-            }
-            if (!empty($fieldDef['length'])) {
-                $options['maxlength'] = min($fieldDef['length'], 100000);
+            if ($maxLength === null && !empty($fieldDef['length'])) {
+                $maxLength = $fieldDef['length'];
             }
+
+            $options['maxlength'] = min($maxLength, 100000);
         }
 
         if (in_array($options['type'], ['datetime', 'date', 'time', 'select'])) {

+ 2 - 3
tests/TestCase/View/Helper/FormHelperTest.php

@@ -9681,10 +9681,9 @@ class FormHelperTest extends TestCase
                 'name' => 'title',
                 'type' => 'text',
                 'required' => 'required',
-                'maxlength' => 45,
+                'maxlength' => 55, // Length set in validator should take precedence over schema.
             ],
             '/div',
-
         ];
         $this->assertHtml($expected, $result);
 
@@ -9715,7 +9714,7 @@ class FormHelperTest extends TestCase
                 'name' => 'title',
                 'type' => 'text',
                 'required' => 'required',
-                'maxlength' => 10,
+                'maxlength' => 10, // Length set in options should take highest precedence.
             ],
             '/div',