Skip to content

Instantly share code, notes, and snippets.

@gherkins
Created March 10, 2012 23:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gherkins/2014023 to your computer and use it in GitHub Desktop.
Save gherkins/2014023 to your computer and use it in GitHub Desktop.
Silverstripe – has_many- and many_many-relations when duplicating pages
<?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