Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 75 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,34 @@
silverstripe-copybutton
=======================
# Copy button for Silverstripe GridFields

Adds a copy/duplicate button to GridFields
Give every row of a GridField a Copy action: one click duplicates the record, and the copy shows up
in the list right away, or opens straight in its edit form. Put it in the row's action menu or show
it as an icon button. For Silverstripe 5 and 6.

![A ModelAdmin GridField of events in the Silverstripe CMS, with a row's action menu open showing Copy above Edit and Delete](docs/images/menu-mode.png)

*Maintained by [Restruct](https://github.com/restruct). If this module saves you time, you can
[support ongoing maintenance](https://github.com/sponsors/restruct).*

## Original author

Elvinas Liutkevičius <elvinas (at) unisolutions (dot) eu>
(Forked from dhensby's SS4-updated fork for quick maintenance & updates/tags)

## Requirements

* Silverstripe 5 or 6 (`silverstripe/framework`)
* PHP 8.1 or newer (Silverstripe 6 itself needs 8.3)

## Installation

```
composer require restruct/silverstripe-copybutton
```

## Version compatibility
## A GridField row cannot be copied out of the box

| Branch | Module version | Silverstripe | PHP |
|--------|----------------|--------------|-----|
| `main` | `3.x` | `^5 \|\| ^6` | `^8.1` |
| `v2` | `2.0.x` | `^4 \|\| ^5 \|\| ^6` (see note) | not declared |
| `1`, `1.0` | `1.x` | `^3` | not declared |
Silverstripe can duplicate a record: `DataObject::duplicate()` does it, relations included where the
model asks for that. The CMS uses it for pages, in the site tree. A GridField, though, has no copy
action: the core row actions view, edit, delete or unlink a record, but none copies it. So an editor who needs a second
event, ticket type or newsletter much like an existing one starts from an empty form and types it
all in again.

`2.0.1` declares Silverstripe 4, 5 and 6 but throws a Silverstripe 6-only exception class when a
user without create permission triggers a copy, so on 4 and 5 that path fatals (issue #3). `3.x`
and the `2.0.2` hotfix fix it. Silverstripe 4 reached end of life in April 2025 and is no longer supported or tested here;
projects still on it should stay on `2.0.x`.
This module adds that missing action:

`main` is the maintained line: it supports every Silverstripe version this module still targets.
The `v2` branch exists only for hotfixes to projects that stay on `^2.0` (such as `2.0.2`).
- **Copy in the row's action menu** (the "..." dropdown), next to Edit and Delete, or as an **icon
button** in the Actions column
- **The copy is written at once** and the GridField re-renders with it in the list
- **Optionally opens the copy's edit form** straight after copying
- **Only offered to users who may create the record** (`canCreate()`), and only for records in the
GridField's own list

**`composer.json` is the source of truth** for exact constraints; this table is a quick reference.
## Copy a row in one click

## Usage
### In the action menu, or as a button

The component is `Unisolutions\GridField\CopyButton`. Add it to a GridField's config:

Expand All @@ -59,6 +47,8 @@ $config->addComponent(CopyButton::create(true), GridFieldEditButton::class);
The one constructor argument is `$useAsColumn` (default `false`): `false` puts "Copy" in the row's
action menu, `true` renders an icon button in the Actions column instead.

![A GridField of ticket types with a copy icon button on every row; the "Family" ticket type is listed twice, the copy right below its original](docs/images/column-mode.png)

Pass the class name, not a short string, as the second `addComponent()` argument: GridFieldConfig
places the component before the first existing component that is an `instanceof` it, and silently
appends it at the end when nothing matches.
Expand All @@ -82,10 +72,11 @@ class MyAdmin extends ModelAdmin
}
```

## What a copy does
### What a copy does

Clicking Copy calls `DataObject::duplicate()` on the record and writes the copy; the GridField then
re-renders with the copy in the list. No edit form is opened, unless you turn on
re-renders with the copy in the list. The copy has the same field values as its original, title
included. No edit form is opened, unless you turn on
[open after copy](#open-the-copy-after-copying).

* **Relations are copied only where the model says so.** `duplicate()` follows the model's
Expand All @@ -97,8 +88,8 @@ re-renders with the copy in the list. No edit form is opened, unless you turn on
the record's `canCreate()` is true. A copy request from anyone else is refused with a
`ValidationException` ("No create permissions") and nothing is written.

To act on the copy - say, to clear some relations - implement `onAfterDuplicate()` on the model or
in an extension. It runs on the **copy**, after it was written:
To act on the copy - say, to clear some relations, or to mark its title as a copy - implement
`onAfterDuplicate()` on the model or in an extension. It runs on the **copy**, after it was written:

```php
use SilverStripe\Core\Extension;
Expand All @@ -112,7 +103,7 @@ class SomeObjectExtension extends Extension
}
```

## Open the copy after copying
### Open the copy after copying

From 3.1, the button can open the copy's edit form straight away instead of re-rendering the list.
It is off by default:
Expand All @@ -124,6 +115,8 @@ use Unisolutions\GridField\CopyButton;
$config->addComponent(CopyButton::create()->setOpenAfterCopy(true), GridFieldEditButton::class);
```

![The edit form of a newsletter in the Silverstripe CMS, opened right after Copy was clicked on its original in the list](docs/images/open-after-copy.png)

The copy opens in the GridField's own detail form (`GridFieldDetailForm`), at the same URL the row's
edit button links to. That works for a GridField in a ModelAdmin and for one nested in a record's
edit form. In the CMS the redirect is answered with an `X-ControllerURL` header, and the admin loads
Expand All @@ -140,9 +133,42 @@ error:
This replaces redirecting from the model's `onAfterDuplicate()`, which fires on every
`duplicate()` call, not only on a click of this button.

## Requirements

* Silverstripe 5 or 6 (`silverstripe/framework`)
* PHP 8.1 or newer (Silverstripe 6 itself needs 8.3)

## Installation

```
composer require restruct/silverstripe-copybutton
```

## Version compatibility

| Branch | Module version | Silverstripe | PHP |
|--------|----------------|--------------|-----|
| `main` | `3.x` | `^5 \|\| ^6` | `^8.1` |
| `v2` | `2.0.x` | `^4 \|\| ^5 \|\| ^6` (see note) | not declared |
| `1`, `1.0` | `1.x` | `^3` | not declared |

`2.0.1` declares Silverstripe 4, 5 and 6 but throws a Silverstripe 6-only exception class when a
user without create permission triggers a copy, so on 4 and 5 that path fatals (issue #3). `3.x`
and the `2.0.2` hotfix fix it. Silverstripe 4 reached end of life in April 2025 and is no longer supported or tested here;
projects still on it should stay on `2.0.x`.

`main` is the maintained line: it supports every Silverstripe version this module still targets.
The `v2` branch exists only for hotfixes to projects that stay on `^2.0` (such as `2.0.2`).

**`composer.json` is the source of truth** for exact constraints; this table is a quick reference.

Upgrading from 2.x: see [UPGRADING.md](UPGRADING.md). What changed in each release:
[CHANGELOG.md](CHANGELOG.md).

## Configuration

The module's only configuration adds its stylesheet to the CMS:
The module's only configuration adds its stylesheet to the CMS (it draws the column-mode icon
button):

```yaml
SilverStripe\Admin\LeftAndMain:
Expand Down Expand Up @@ -170,13 +196,23 @@ SS_PHPUNIT_FLUSH=1 vendor/bin/phpunit vendor/restruct/silverstripe-copybutton/te

CI runs the same suite against Silverstripe 5 and 6 on pushes to `main` and on pull requests; see `.github/workflows/ci.yml`.

Playwright browser tests in `tests/browser/` click the copy button in a real CMS, on Silverstripe 5
and 6, in CI (`.github/workflows/browser-tests.yml`). The screenshots in this README are generated
the same way, from neutral demo content; see
[tests/browser/screenshots/README.md](tests/browser/screenshots/README.md) to regenerate them.

## Relation to dhensby/silverstripe-copybutton

This package `replace`s `dhensby/silverstripe-copybutton` (and `unisolutions/silverstripe-copybutton`):
all three ship the same class, so only one of them can be installed. Upstream publishes its own
Silverstripe 6-only 3.0.0; this package's 3.x covers Silverstripe 5 and 6 and differs in behaviour
(see [CHANGELOG.md](CHANGELOG.md)).

## Original author

Elvinas Liutkevičius <elvinas (at) unisolutions (dot) eu>
(Forked from dhensby's SS4-updated fork for quick maintenance & updates/tags)

## Licence

BSD-3-Clause, see [LICENSE](LICENSE).
8 changes: 5 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
"name": "restruct/silverstripe-copybutton",
"type": "silverstripe-vendormodule",
"license": "BSD-3-Clause",
"description": "Adds copy/duplicate button to the GridField.",
"description": "A Copy action for Silverstripe GridField rows: duplicate a record in one click, from the row action menu or an icon button, and optionally open the copy.",
"keywords": [
"silverstripe",
"copy",
"button",
"silverstripe-module",
"silverstripe-cms",
"gridfield",
"modeladmin",
"copy",
"duplicate"
],
"authors": [
Expand Down
Binary file added docs/images/column-mode.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/menu-mode.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/open-after-copy.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
56 changes: 56 additions & 0 deletions tests/browser/playwright.screenshots.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { defineConfig, devices } from '@playwright/test';

// README screenshots, NOT tests: writes docs/images/*.png from a Silverstripe 6 host with the
// screenshot fixtures (screenshots/fixtures/) loaded. Kept apart from playwright.config.ts on
// purpose: the browser tests (and CI) run that config, and must never rewrite docs/images/.
// How to run: screenshots/README.md.

// The same BROWSER_TARGET_URLS format the runner uses, but only ONE target is used: two targets
// would overwrite each other's images. ss6 when present, else the first one.
const targets = (process.env.BROWSER_TARGET_URLS ?? '')
.split(',')
.map((pair) => pair.trim())
.filter(Boolean)
.map((pair) => {
const [name, url] = pair.split('=');
return { name, url };
});
const target = targets.find((t) => t.name === 'ss6') ?? targets[0];

if (!target) {
throw new Error(
'BROWSER_TARGET_URLS is empty. See screenshots/README.md, e.g. ' +
'BROWSER_TARGET_URLS="ss6=http://127.0.0.1:8958"',
);
}

export default defineConfig({
testDir: '.',
outputDir: './test-results',
retries: 0,
// One admin session, shared; see playwright.config.ts for why that means one worker.
workers: 1,
timeout: 60_000,
expect: { timeout: 10_000 },
reporter: [['list']],
use: {
...devices['Desktop Chrome'],
// ~1280 wide, at 1x, so the PNGs are the width a README shows them at.
viewport: { width: 1280, height: 720 },
deviceScaleFactor: 1,
screenshot: 'only-on-failure',
},
projects: [
{
name: `${target.name}-login`,
testMatch: /specs\/login\.setup\.ts/,
use: { baseURL: target.url },
},
{
name: target.name,
testMatch: /screenshots\/.*\.shot\.ts/,
dependencies: [`${target.name}-login`],
use: { baseURL: target.url, storageState: `.auth/${target.name}.json` },
},
],
});
35 changes: 35 additions & 0 deletions tests/browser/screenshots/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# README screenshots

`readme.shot.ts` writes the PNGs in `docs/images/` that the module README shows. It is not a test
suite: it runs with its own config, `playwright.screenshots.config.ts`, which the browser tests and
CI never load, so a normal test run never rewrites the images. Never edit the PNGs by hand;
regenerate them.

The content is neutral demo data, not the browser-test fixtures: the PHP classes in `fixtures/`
here add an "Events" ModelAdmin (`/admin/events`) with one tab per copy-button setup, re-seeded on
every database build:

- Events: menu mode, `CopyButton::create()`
- Ticket types: column mode, `CopyButton::create(true)`
- Newsletters: menu mode with `setOpenAfterCopy(true)`

What it needs:

- a Silverstripe 6 host with this module installed as a symlinked path repository (the browser-test
runner's host works, or any scratch project), with the PHP files from `fixtures/` here copied into
its `app/src/`, then `vendor/bin/sake db:build --flush`. Build the database again before every
run: the script makes copies, and the column-mode shot expects exactly one;
- the host served (PHP's built-in server with a router that passes static files through, such as
`../router.php`), with a default admin `admin` / `admin`, which `specs/login.setup.ts` logs in as;
- `BROWSER_TARGET_URLS` pointing at that host (only the `ss6` target is used, else the first).

Then, from `tests/browser/`:

```bash
npm ci
BROWSER_TARGET_URLS="ss6=http://127.0.0.1:8958" npx playwright test --config=playwright.screenshots.config.ts
```

The shared runner's helpers in the maintainers' workspace (`tools/browser/lib.sh`: `host_ensure`,
`host_link_module`, `host_sync_fixtures` with this `fixtures/` directory, `host_build_db`,
`host_start`) build and serve such a host.
48 changes: 48 additions & 0 deletions tests/browser/screenshots/fixtures/ShotAdmin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace Restruct\CbShots;

use SilverStripe\Admin\ModelAdmin;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldEditButton;
use Unisolutions\GridField\CopyButton;

/**
* README-SCREENSHOT FIXTURE ONLY (see ShotEvent) - the CMS screen the README screenshots show:
* /admin/events/<tab>, one tab per copy-button setup, configured the way the README tells a
* project to.
*/
class ShotAdmin extends ModelAdmin
{
private static $url_segment = 'events';

private static $menu_title = 'Events';

private static $menu_icon_class = 'font-icon-calendar';

# Keyed managed_models: the key becomes the URL segment and the GridField's name.
private static $managed_models = [
'events' => ['dataClass' => ShotEvent::class, 'title' => 'Events'],
'tickets' => ['dataClass' => ShotTicketType::class, 'title' => 'Ticket types'],
'newsletters' => ['dataClass' => ShotNewsletter::class, 'title' => 'Newsletters'],
];

protected function getGridFieldConfig(): GridFieldConfig
{
$config = parent::getGridFieldConfig();

switch ($this->modelClass) {
case ShotEvent::class:
$config->addComponent(CopyButton::create(), GridFieldEditButton::class);
break;
case ShotTicketType::class:
$config->addComponent(CopyButton::create(true), GridFieldEditButton::class);
break;
case ShotNewsletter::class:
$config->addComponent(CopyButton::create()->setOpenAfterCopy(true), GridFieldEditButton::class);
break;
}

return $config;
}
}
Loading
Loading