Created
March 10, 2012 23:41
-
-
Save gherkins/2014023 to your computer and use it in GitHub Desktop.
Silverstripe – has_many- and many_many-relations when duplicating pages
This file contains 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