浏览代码

[Form] FieldGroup::addError() can now map errors to fields within nested FieldGroups

Property paths such as fields[group].fields[innerGroup].data were not being resolved correctly, since the second iteration of addError() (based on "group") would attempt to call get('fields') instead of get('innerGroup').  Solution is to remember to bump the propertyPath forward if we're at the fields property
Jeremy Mikola 15 年之前
父节点
当前提交
fb24b291c8
共有 2 个文件被更改,包括 19 次插入0 次删除
  1. 4 0
      src/Symfony/Component/Form/FieldGroup.php
  2. 15 0
      tests/Symfony/Tests/Component/Form/FieldGroupTest.php

+ 4 - 0
src/Symfony/Component/Form/FieldGroup.php

@@ -373,6 +373,10 @@ class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterfac
             if ($type === self::FIELD_ERROR && $path->hasNext()) {
                 $path->next();
 
+                if ($path->isProperty() && $path->getCurrent() === 'fields') {
+                    $path->next();
+                }
+
                 if ($this->has($path->getCurrent()) && !$this->get($path->getCurrent())->isHidden()) {
                     $this->get($path->getCurrent())->addError($message, $path, $type);
 

+ 15 - 0
tests/Symfony/Tests/Component/Form/FieldGroupTest.php

@@ -156,6 +156,21 @@ class FieldGroupTest extends \PHPUnit_Framework_TestCase
         $group->addError('Message', new PropertyPath('fields[firstName].data'), FieldGroup::FIELD_ERROR);
     }
 
+    public function testAddErrorMapsFieldValidationErrorsOntoFieldsWithinNestedFieldGroups()
+    {
+        $field = $this->createMockField('firstName');
+        $field->expects($this->once())
+                    ->method('addError')
+                    ->with($this->equalTo('Message'));
+
+        $group = new FieldGroup('author');
+        $innerGroup = new FieldGroup('names');
+        $innerGroup->add($field);
+        $group->add($innerGroup);
+
+        $group->addError('Message', new PropertyPath('fields[names].fields[firstName].data'), FieldGroup::FIELD_ERROR);
+    }
+
     public function testAddErrorKeepsFieldValidationErrorsIfFieldNotFound()
     {
         $field = $this->createMockField('foo');