diff --git a/code/model/SiteTree.php b/code/model/SiteTree.php index 36444e58..aa804961 100755 --- a/code/model/SiteTree.php +++ b/code/model/SiteTree.php @@ -699,11 +699,14 @@ class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvid $children = $this->AllChildren(); if($children) { + $sort = 0; foreach($children as $child) { $childClone = method_exists($child, 'duplicateWithChildren') ? $child->duplicateWithChildren() : $child->duplicate(); $childClone->ParentID = $clone->ID; + //retain sort order by manually setting sort values + $childClone->Sort = ++$sort; $childClone->write(); } } diff --git a/tests/model/SiteTreeTest.php b/tests/model/SiteTreeTest.php index fd65ecae..93ad7157 100644 --- a/tests/model/SiteTreeTest.php +++ b/tests/model/SiteTreeTest.php @@ -342,6 +342,39 @@ class SiteTreeTest extends SapphireTest { $this->assertStringEndsWith('changed-on-live/my-staff/?stage=Live', $child->getAbsoluteLiveLink()); } + public function testDuplicateChildrenRetainSort() { + $parent = new Page(); + $parent->Title = 'Parent'; + $parent->write(); + + $child1 = new Page(); + $child1->ParentID = $parent->ID; + $child1->Title = 'Child 1'; + $child1->Sort = 2; + $child1->write(); + + $child2 = new Page(); + $child2->ParentID = $parent->ID; + $child2->Title = 'Child 2'; + $child2->Sort = 1; + $child2->write(); + + $duplicateParent = $parent->duplicateWithChildren(); + $duplicateChildren = $duplicateParent->AllChildren()->toArray(); + $this->assertCount(2, $duplicateChildren); + + $duplicateChild2 = array_shift($duplicateChildren); + $duplicateChild1 = array_shift($duplicateChildren); + + + $this->assertEquals('Child 1', $duplicateChild1->Title); + $this->assertEquals('Child 2', $duplicateChild2->Title); + + // assertGreaterThan works by having the LOWER value first + $this->assertGreaterThan($duplicateChild2->Sort, $duplicateChild1->Sort); + + } + public function testDeleteFromStageOperatesRecursively() { Config::inst()->update('SiteTree', 'enforce_strict_hierarchy', false); $pageAbout = $this->objFromFixture('Page', 'about');