RSS Feed
^__^

Silverstripe – has_many- and many_many-relations when duplicating pages

,

When you duplicate a page in the Silverstripe Sitetree, related “has_one” Items are automatically copied, which is nice.

But if you have, lets say, multiple related images on that Page, those are not copied when you duplicate that Page.

After reading this discussion, i found out that it’s actually pretty easy to “fix” this.

This what i ended up with and seems to be working fine:

//assuming your page has the following related Dataobjects

public static $has_many = array(
'Images' => 'MyImageDataObject'
);

public static $many_many = array(
'Something' => 'AnotherPageTypeOrWhatever

);

The following code would automatically duplicate the has_many related DataObjects
and just set the relation to the many_many Objects on the created page:

..as already suggested in the forum, i still think this would make a handy core feature, wouldn’t it?
Would be cool to globally specify relations to duplicate in the page-config with something like

public static $relations_to_copy = array(
 'Images',
 'Somehting'
);

One Response to “Silverstripe – has_many- and many_many-relations when duplicating pages”

  1. Hi Max,

    Just came across this post, i’m the one who asked the question on the forum, that you were so kind to answer.

    I still use this code, it’s very handy. Maybe someone could write this into a module? But perhaps it will not be needed in SS3.

    Just found this kinda related info, which is about copying relations when creating translations – the post is here:
    http://www.silverstripe.org/general-questions/show/19990

    The code (you might want to add this to your post):
    Added the following code at the end of the function createTranslation($locale) in Translatable.php

    foreach( $originalPage->many_many() as $key => $className ){
    $newTranslation->{$key}()->addMany($originalPage->{$key}()->getIdList());
    }
    

    Regards,
    Thomas – Nobrainer Web

Leave a Reply