Procházet zdrojové kódy

Fixes #319 - Zend_Form::hasErrors() could check for errors on the fly

Frank Brückner před 11 roky
rodič
revize
f9402f5347
2 změnil soubory, kde provedl 65 přidání a 1 odebrání
  1. 21 1
      library/Zend/Form.php
  2. 44 0
      tests/Zend/Form/FormTest.php

+ 21 - 1
library/Zend/Form.php

@@ -2494,7 +2494,27 @@ class Zend_Form implements Iterator, Countable, Zend_Validate_Interface
      */
     public function hasErrors()
     {
-        return $this->_errorsExist;
+        $errors = $this->_errorsExist;
+
+        if (!$errors) {
+            /** @var Zend_Form_Element $element */
+            foreach ($this->getElements() as $element) {
+                if ($element->hasErrors()) {
+                    $errors = true;
+                    break;
+                }
+            }
+
+            /** @var Zend_Form_SubForm $subForm */
+            foreach ($this->getSubForms() as $subForm) {
+                if ($subForm->hasErrors()) {
+                    $errors = true;
+                    break;
+                }
+            }
+        }
+
+        return $errors;
     }
 
     /**

+ 44 - 0
tests/Zend/Form/FormTest.php

@@ -4815,6 +4815,50 @@ class Zend_Form_FormTest extends PHPUnit_Framework_TestCase
 
         $this->assertEquals($expected, $actual);
     }
+
+    /**
+     * @group GH-319
+     */
+    public function testHasErrorsMethodShouldCheckAlsoElements()
+    {
+        // Init form
+        $form    = new Zend_Form();
+        $element = new Zend_Form_Element_Text('foo');
+        $form->addElement($element);
+
+        $element->markAsError();
+
+        // Test form
+        $this->assertTrue($form->hasErrors());
+        $this->assertFalse($form->isValid(array('foo' => 1)));
+
+        // Test element
+        $this->assertTrue($element->hasErrors());
+        $this->assertFalse($element->isValid(1));
+    }
+
+    /**
+     * @group GH-319
+     */
+    public function testHasErrorsMethodShouldCheckAlsoSubForms()
+    {
+        // Init form
+        $form    = new Zend_Form();
+        $subForm = new Zend_Form_SubForm();
+        $element = new Zend_Form_Element_Text('foo');
+        $subForm->addElement($element);
+        $form->addSubForm($subForm, 'subForm');
+
+        $element->markAsError();
+
+        // Test form
+        $this->assertTrue($form->hasErrors());
+        $this->assertFalse($form->isValid(array('foo' => 1)));
+
+        // Test element
+        $this->assertTrue($element->hasErrors());
+        $this->assertFalse($element->isValid(1));
+    }
 }
 
 class Zend_Form_FormTest_DisplayGroup extends Zend_Form_DisplayGroup