浏览代码

[Form] Fixed RepeatedField not to trigger NotNull/NotBlank errors if any of the fields was filled in

Bernhard Schussek 14 年之前
父节点
当前提交
a725415440
共有 2 个文件被更改,包括 23 次插入7 次删除
  1. 13 6
      src/Symfony/Component/Form/RepeatedField.php
  2. 10 1
      tests/Symfony/Tests/Component/Form/RepeatedFieldTest.php

+ 13 - 6
src/Symfony/Component/Form/RepeatedField.php

@@ -86,16 +86,23 @@ class RepeatedField extends Form
     }
 
     /**
-     * Return only value of first password field.
+     * Return the value of a child field
      *
-     * @return string The password.
+     * If the value of the first field is set, this value is returned.
+     * Otherwise the value of the second field is returned. This way,
+     * this field will never trigger a NotNull/NotBlank error if any of the
+     * child fields was filled in.
+     *
+     * @return string The field value
      */
     public function getData()
     {
-        if ($this->isSubmitted() && $this->isFirstEqualToSecond()) {
-            return $this->get($this->getOption('first_key'))->getData();
-        }
+        // Return whichever data is set. This should not return NULL if any of
+        // the fields is set, otherwise this might trigger a NotNull/NotBlank
+        // error even though some value was set
+        $data1 = $this->get($this->getOption('first_key'))->getData();
+        $data2 = $this->get($this->getOption('second_key'))->getData();
 
-        return null;
+        return $data1 ?: $data2;
     }
 }

+ 10 - 1
tests/Symfony/Tests/Component/Form/RepeatedFieldTest.php

@@ -43,7 +43,7 @@ class RepeatedFieldTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals('bar', $this->field['second']->getDisplayedData());
         $this->assertFalse($this->field->isFirstEqualToSecond());
         $this->assertEquals($input, $this->field->getDisplayedData());
-        $this->assertEquals(null, $this->field->getData());
+        $this->assertEquals('foo', $this->field->getData());
     }
 
     public function testSubmitEqual()
@@ -58,4 +58,13 @@ class RepeatedFieldTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals($input, $this->field->getDisplayedData());
         $this->assertEquals('foo', $this->field->getData());
     }
+
+    public function testGetDataReturnsSecondValueIfFirstIsEmpty()
+    {
+        $input = array('first' => '', 'second' => 'bar');
+
+        $this->field->submit($input);
+
+        $this->assertEquals('bar', $this->field->getData());
+    }
 }