Forked from gherkins/silverstripe_duplicate_relations.php
Created
July 7, 2016 23:22
-
-
Save roartalent/51185d6f399d6ff3edfa9f0290816a9c to your computer and use it in GitHub Desktop.
Silverstripe – has_many- and many_many-relations when duplicating pages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function duplicate() { | |
$items_to_duplicate = array( | |
'Images', | |
'Somehting' | |
); | |
$page = parent::duplicate(); | |
//duplicate has many items | |
foreach ($this->has_many() as $key => $className) { | |
if (in_array($key, $items_to_duplicate)) { | |
foreach ($this->{$key}() as $item) { | |
$newField = $item->duplicate(); | |
$id = get_class($this) . 'ID'; | |
$newField->{$id} = $page->ID; | |
$newField->write(); | |
} | |
} | |
} | |
//set the relation to many_many items on created page | |
foreach ($this->many_many() as $key => $className) { | |
if (in_array($key, $items_to_duplicate)) { | |
$page->{$key}()->addMany($this->{$key}()->getIdList()); | |
} | |
} | |
return $page; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment