Permalink
Browse files

[hotfix/ZF-11402] Zend\Form\Element

Zend\Form\Element\MultiCheckbox does not accept empty array even when AllowEmpty flag is set
  • Loading branch information...
1 parent 5e13bbc commit 75048490f98d3d5aac67ae76d4c7dc22bb18e616 @adamlundrigan committed Nov 4, 2011
Showing with 48 additions and 2 deletions.
  1. +9 −2 library/Zend/Form/Element.php
  2. +39 −0 tests/Zend/Form/Element/MultiCheckboxTest.php
@@ -1373,15 +1373,22 @@ public function isValid($value, $context = null)
if ($isArray && is_array($value)) {
$messages = array();
$errors = array();
- foreach ($value as $val) {
+ if (empty($value)) {
+ if ($this->isRequired()
+ || (!$this->isRequired() && !$this->getAllowEmpty())
+ ) {
+ $value = '';
+ }
+ }
+ foreach ((array)$value as $val) {
if (!$validator->isValid($val, $context)) {
$result = false;
if ($this->_hasErrorMessages()) {
$messages = $this->_getErrorMessages();
$errors = $messages;
} else {
$messages = array_merge($messages, $validator->getMessages());
- $errors = array_merge($errors, $validator->getErrors());
+ $errors = $messages;
}
}
}
@@ -250,4 +250,43 @@ public function testRetrievingErrorMessagesShouldNotResultInError()
$this->element->isValid(array('foo', 'bogus'));
$html = $this->element->render($this->getView());
}
+
+ /**
+ * @group ZF-11402
+ */
+ public function testValidateShouldNotAcceptEmptyArray()
+ {
+ $this->element->addMultiOptions(array(
+ 'foo' => 'Foo',
+ 'bar' => 'Bar',
+ 'baz' => 'Baz',
+ ));
+ $this->element->setRegisterInArrayValidator(true);
+
+ $this->assertTrue($this->element->isValid(array('foo')));
+ $this->assertTrue($this->element->isValid(array('foo','baz')));
+
+ $this->element->setAllowEmpty(true);
+ $this->assertTrue($this->element->isValid(array()));
+
+ // Empty value + AllowEmpty=true = no error messages
+ $messages = $this->element->getMessages();
+ $this->assertEquals(0, count($messages), 'Received unexpected error message(s)');
+
+ $this->element->setAllowEmpty(false);
+ $this->assertFalse($this->element->isValid(array()));
+
+ // Empty value + AllowEmpty=false = notInArray error message
+ $messages = $this->element->getMessages();
+ $this->assertTrue(is_array($messages), 'Expected error message');
+ $this->assertArrayHasKey('notInArray', $messages, 'Expected \'notInArray\' error message');
+
+ $this->element->setRequired(true)->setAllowEmpty(false);
+ $this->assertFalse($this->element->isValid(array()));
+
+ // Empty value + Required=true + AllowEmpty=false = isEmpty error message
+ $messages = $this->element->getMessages();
+ $this->assertTrue(is_array($messages), 'Expected error message');
+ $this->assertArrayHasKey('isEmpty', $messages, 'Expected \'isEmpty\' error message');
+ }
}

0 comments on commit 7504849

Please sign in to comment.