← Posts

Under the hood of the Duplicator addon

May 21st, 2022 - 5 min read

Duplicator is by far my most popular Statamic addon, by downloads at least. And to be honest, it's probably one of my simplest.

Duplicator registers a few actions: one for each of the 'things' you can delete - an entry, an asset, a term and soon (hopefully) a form.

Actions are what you see when you click the 'three dots' on the listing tables:


Today, I'm going to walk you through the action for duplicating entries (which is probably the one used most often). So let's dig in:

1public static function title()
3 return __('duplicator::messages.duplicate');

I thought I'd start off easy. That just returns the title of the action which is the text that's displayed on the 'actions dropdown in the CP.

We're making use of Laravel's __ method here which lets us 'localise' the text so it can be 'Duplicate' but in whatever language the current Control Panel user is using.

The community has contributed translations for a few languages - you can review the docs here on what languages are supported and how to add your own.

1protected function fieldItems()
3 if (Site::all()->count() > 1) {
4 return [
5 'site' => [
6 'type' => 'select',
7 'instructions' => __('duplicator::messages.fields.site.instructions'),
8 'validate' => 'required|in:all,' . Site::all()->keys()->join(','),
9 'options' => Site::all()
10 ->map(function (SitesSite $site) {
11 return $site->name();
12 })
13 ->prepend(__('duplicator::messages.fields.site.all_sites'), 'all')
14 ->toArray(),
15 'default' => 'all',
16 ],
17 ];
18 }
20 return [];

Actions can optionally use the fieldItems method to return any fields which should be shown to the user before the action is run.

If Duplicator is running on a multi-site, it'll show a 'Site' dropdown field which gives the user the option of duplicating the selected entry to a specific site or even all sites.


We'll get onto how the multisite duplicating works in a little bit.

1public function visibleTo($item)
3 return $item instanceof AnEntry;
6public function visibleToBulk($items)
8 return $this->visibleTo($items->first());

These two methods (visibleTo and visibleToBulk) are where you decide whether an action is shown/visible for a certain item(s). An item could be an Entry, a Term, an Asset, etc.

The visibleTo method expects a single item to be passed in. We then check whether the $item is an instance of the Entry object. If it is, we'll return true to tell Statamic our 'Duplicate' action should show in the Actions List.

The second method, visibleToBulk does pretty much the same thing but multiple items are passed into it.

Because I was lazy when I wrote this, we're just calling the other method for the first item in the $items collection. In some of my other addons, I map through the $items, pass it through the visibleTo, then check the count of them being true is the same as the original count of the $items collection.

The visibleToBulk method is called when you select multiple entries in the Listing Table - which then displays the available Actions at the top of the table.


1public function run($items, $values)
3 collect($items)
4 ->each(function ($item) use ($values) {
5 /** @var \Statamic\Entries\Entry $item */
6 if ($item instanceof AnEntry) {
7 $itemParent = $this->getEntryParentFromStructure($item);
8 $itemTitleAndSlug = $this->generateTitleAndSlug($item);
10 $entry = Entry::make()
11 ->collection($item->collection())
12 ->blueprint($item->blueprint()->handle())
13 ->locale(isset($values['site']) && $values['site'] !== 'all' ? $values['site'] : $item->locale())
14 ->published(config('duplicator.defaults.published', $item->published()))
15 ->slug($itemTitleAndSlug['slug'])
16 ->data(
17 $item->data()
18 ->except(config("duplicator.ignored_fields.entries.{$item->collectionHandle()}"))
19 ->merge([
20 'title' => $itemTitleAndSlug['title'],
21 ])
22 ->toArray()
23 );
25 if ($item->hasDate()) {
26 $entry->date($item->date());
27 }
29 if (config('duplicator.fingerprint') === true) {
30 $entry->set('is_duplicate', true);
31 }
33 $entry->save();
35 if ($itemParent && $itemParent !== $item->id()) {
36 $entry->structure()
37 ->in(isset($values['site']) && $values['site'] !== 'all' ? $values['site'] : $item->locale())
38 ->appendTo($itemParent->id(), $entry)
39 ->save();
40 }
42 if (isset($values['site']) && $values['site'] === 'all') {
43 Site::all()
44 ->reject(function ($site) use ($entry) {
45 return $site->handle() === $entry->locale();
46 })
47 ->each(function ($site) use ($entry) {
48 $entry->makeLocalization($site->handle())->save();
49 });
50 }
51 }
52 });

And here we are... the meat of the article. How Duplicator does the duplicating!

Because an action can be run on multiple items at once, the first thing we're doing is looping through each of the $items with a Laravel Collection.

Next, we check if the current $item is actually an Entry instance (in case, somehow the visibleTo stuff didn't work).

After that, we then call two custom methods: getEntryParentFromStructure which figures out the entry's parent from the collection's tree, then the second, generateTitleAndSlug generates a title and slug for the duplicated entry. We'll discuss how both of these methods work individually later on.

Next, we start building an Entry object. We set the collection, the blueprint, the locale/site for it to be duplicated into, the publish status, the slug we just made, along with 'entry data'.

After that, we check if the entry collection has dates enabled. If it does, we set the date of the duplicated entry to the date of the original entry.

Duplicator has a concept of 'fingerprints' which essentially means it leaves a is_duplicate key on the entry so you can tell if an entry was created by Duplicator.

We then save the entry! 🎉

After it's saved, we do a couple more things:

1protected function getEntryParentFromStructure(AnEntry $entry)
3 if (! $entry->structure()) {
4 return null;
5 }
7 $parentEntry = $entry
8 ->structure()
9 ->in($entry->locale())
10 ->page($entry->id())
11 ->parent();
13 if (! $parentEntry) {
14 return null;
15 }
17 if ($entry->structure()->expectsRoot() && $entry->structure()->in($entry->locale())->root()['entry'] === $parentEntry->id()) {
18 return null;
19 }
21 return $parentEntry;

Here's the first of our two custom methods. As described above, this method figures out the parent of the original entry in the collection's tree.

If the collection doesn't have a tree, we'll just return early.

Otherwise, we'll get the instance of the original entry in the tree, then we'll call the ->parent() method on it.

If the original entry has no parent in the collection tree, we also then just return early.

We then do another check to see if the original entry was the 'root page' in the collection tree (eg. a homepage). If it is, we also just return early as we can't have two root pages 😅.

If we make it this far, we simply return the parent entry.

2 * This method has been copied from the Duplicate Entry code in Statamic v2.
3 * It's been updated to also deal with entry titles.
4 */
5protected function generateTitleAndSlug(AnEntry $entry, $attempt = 1)
7 $title = $entry->get('title');
8 $slug = $entry->slug();
10 if ($attempt == 1) {
11 $title = $title . __('duplicator::messages.duplicated_title');
12 }
14 if ($attempt !== 1) {
15 if (! Str::contains($title, __('duplicator::messages.duplicated_title'))) {
16 $title .= __('duplicator::messages.duplicated_title');
17 }
19 $title .= ' (' . $attempt . ')';
20 }
22 $slug .= '-' . $attempt;
24 // If the slug we've just built already exists, we'll try again, recursively.
25 if (Entry::findBySlug($slug, $entry->collection()->handle())) {
26 $generate = $this->generateTitleAndSlug($entry, $attempt + 1);
28 $title = $generate['title'];
29 $slug = $generate['slug'];
30 }
32 return [
33 'title' => $title,
34 'slug' => $slug,
35 ];

And here's the second custom method...

This one generates the title & slug for duplicate entries. You might notice that if you duplicate the same entry multiple times, you get titles/slugs like Entry #1, Entry #2, Entry #3. This is the method that figures how many duplicates you've previously made and adjusts the title.

I copied this code from Statamic v2 (it had Duplicator's functionality built into Core).

The first thing this method does is assigns the title & slug of the original entry to variables.

Then, it'll generate a title based on the $attempt variable. So, $attempt being 5 would generate Entry #5.

It then checks if there's any existing entries in the collection with that title. If there is, it calls itself again, and ups the $attempt by 1. It does this until it finds a unique title/slug it can use, which it then returns.

There you go! I've literally given you all the code to build your own Duplicator addon. Hopefully that's been a helpful learning experience for you - diving into how Actions work & how to interact with some of Statamic's internal APIs.