Browse Source

Added method getError() to Form #17219

leon.schaub 2 years ago
parent
commit
5368eda88b
2 changed files with 19 additions and 1 deletions
  1. 11 0
      src/Form/Form.php
  2. 8 1
      tests/TestCase/Form/FormTest.php

+ 11 - 0
src/Form/Form.php

@@ -236,6 +236,17 @@ class Form implements EventListenerInterface, EventDispatcherInterface, Validato
     }
 
     /**
+     * Returns validation errors for the given field
+     *
+     * @param string $field Field name to get the errors from.
+     * @return array The validation errors for the given field.
+     */
+    public function getError(string $field): array
+    {
+        return $this->_errors[$field] ?? [];
+    }
+
+    /**
      * Set the errors in the form.
      *
      * ```

+ 8 - 1
tests/TestCase/Form/FormTest.php

@@ -140,7 +140,7 @@ class FormTest extends TestCase
     }
 
     /**
-     * Test the get errors methods.
+     * Test the get errors & get error methods.
      */
     public function testGetErrors(): void
     {
@@ -160,10 +160,17 @@ class FormTest extends TestCase
             'body' => 'too short',
         ];
         $form->validate($data);
+
         $errors = $form->getErrors();
         $this->assertCount(2, $errors);
         $this->assertSame('Must be a valid email', $errors['email']['format']);
         $this->assertSame('Must be so long', $errors['body']['length']);
+
+        $error = $form->getError('email');
+        $this->assertSame(['format' => 'Must be a valid email'], $error);
+
+        $error = $form->getError('foo');
+        $this->assertSame([], $error);
     }
 
     /**