restruct / silverstripe-editor-datafields
TinyMCE plugin for placeholder data fields in the HTML editor, stored as template tags and live-updated from static or form-driven values
Package info
github.com/restruct/silverstripe-editor-datafields
Language:JavaScript
Type:silverstripe-vendormodule
pkg:composer/restruct/silverstripe-editor-datafields
Fund package maintenance!
Requires
- php: ^8.1
- silverstripe/admin: ^2 || ^3
- silverstripe/framework: ^5 || ^6
- silverstripe/vendor-plugin: ^2 || ^3
Requires (Dev)
None
Suggests
- silverstripe/htmleditor-tinymce: Required on Silverstripe 6: the TinyMCE editor moved out of silverstripe/admin into this module
Provides
None
Conflicts
None
Replaces
None
README
A TinyMCE plugin for Silverstripe that lets editors drop placeholders ("data fields") such as the
recipient's name or an appointment date into an HTML editor field. In the editor each placeholder shows
as a highlighted, non-editable sample value; in the saved HTML it is a plain template tag
({$Recipient.FirstName}), so it is filled in with real data when the content is rendered. The sample
values can follow the form around the editor live: pick another sender in a dropdown and every
placeholder for the sender updates in the text.
Maintained by Restruct. If this module saves you time, you can support ongoing maintenance.
Templated text without template syntax
Letters, e-mails, documents and status updates written in the CMS often need a few values that differ
per recipient or per case. Asking editors to type {$Contact.FirstName} by hand is error-prone, and the
raw tag tells them nothing about what the text will look like. This plugin gives them a toolbar dropdown
of the available fields, shows a readable value in place of each tag, and keeps the tag intact so it
cannot be half-edited by accident.
What it does
- Insert dropdown ("Data fields" toolbar button) listing the configured fields.
- Placeholders as non-editable spans in the editor, saved as
{$Field.Path}template tags. - Static sample values per editor, for example the actual recipient's data, passed in a data attribute.
- Dynamic sample values that follow
<input>and<select>fields elsewhere on the form, live. - Double-click a placeholder to turn it into ordinary editable text (it is then no longer replaced).
- Merge tags (
mergetagsplugin): a second, simpler dropdown that inserts literal tag text, with optional sub-menus.
Requirements and compatibility
composer.json is the source of truth; this table is a convenience copy.
| Branch | Module version | Silverstripe | TinyMCE | PHP |
|---|---|---|---|---|
main |
2.x | 5.4, 6 | 6 | 8.1 and up |
v1 |
1.x | 4 | 4 | 7.4, 8.x |
On Silverstripe 6 the HTML editor is a separate module, silverstripe/htmleditor-tinymce; a project that
uses HTML editor fields already has it. On Silverstripe 5 TinyMCE ships with silverstripe/admin.
Installation
composer require restruct/silverstripe-editor-datafields
The plugin scripts in client/ are exposed by silverstripe/vendor-plugin (on install, or with
composer vendor-expose) to _resources/vendor/restruct/silverstripe-editor-datafields/client/.
Configuration
1. Declare the fields
Set the datafields option on the editor config the field uses. Each entry has:
| Key | Required | Meaning |
|---|---|---|
field |
yes | Field path written into the tag, eg Contact.FirstName gives {$Contact.FirstName} |
text |
no | Label in the insert dropdown (default: field) |
value |
no | Sample value shown in the editor (default: text). HTML; newlines become <br> |
Extra keys are ignored by the plugin and kept on the option, so a project can keep its own metadata on
the same entries (for example how to render each field) and read it back with getOption('datafields').
use Restruct\HTMLEditor\DataFields\HTMLEditorConfigHelper; use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig; # A separate editor config, so the CMS default config stays untouched HTMLEditorConfigHelper::duplicate_config('cms', 'letters'); HTMLEditorConfigHelper::apply_datafields_base('letters'); HTMLEditorConfig::get('letters')->setOption('datafields', [ ['field' => 'Contact.FirstName', 'text' => 'Recipient first name', 'value' => 'First name'], ['field' => 'Contact.FullName', 'text' => 'Recipient name', 'value' => 'Full name'], ['field' => 'Sender.FullName', 'text' => 'Sender name', 'value' => 'Sender'], ]);
Then use that config on the field: HTMLEditorField::create('Body')->setEditorConfig('letters').
Helper API (HTMLEditorConfigHelper)
All methods are static and take the name of an editor config.
| Method | What it does |
|---|---|
duplicate_config($existing, $new) |
Copies options, plugins and toolbar buttons of an editor config to a new named config, and returns it |
apply_datafields_base($config, $lineOrButton = 2) |
Enables the datafields plugin and adds its button: to toolbar line $lineOrButton (an int), or after the button of that name (a string; end of line 1 if that button is absent). Also makes sure the config allows the placeholder spans (see below). Returns the config |
apply_mergetags_base($config, $lineOrButton = 2) |
The same for the mergetags plugin |
plugin_url($plugin = 'datafields') |
The exposed URL of datafields.js or mergetags.js, for a TinyMCE you initialise yourself |
get_config_property($config, $property) |
Reads a non-public property of an editor config |
Restricted valid_elements. The placeholders are <span class="mceNonEditable" data-datafield="...">
elements. If the config has its own valid_elements without span (or without its class), TinyMCE would
drop them. apply_datafields_base() therefore merges span[class|data-datafield] with the span rule the
config already has, and writes the result to extended_valid_elements. A config without valid_elements
(TinyMCE's own schema) is left alone. The saved HTML contains no spans, only the template tags.
2. Render the content
The saved HTML contains plain template tags. Render it against the record that holds the data:
use SilverStripe\View\SSViewer; $html = SSViewer::fromString($letter->Body)->process($recipientRecord);
The data attribute contract
All of these are optional and go on the editor's <textarea> (the HTMLEditorField) unless stated
otherwise. Values are JSON.
| Attribute | On | Format | Effect |
|---|---|---|---|
data-datafields |
editor | [{"field": ..., "text": ..., "value": ...}] |
Replaces the datafields config option for this editor |
data-datafields-static-tokenvalues |
editor | [{"field": "Contact.FirstName", "value": "Anna"}] |
Sets the sample value of those fields |
data-datafields-dynamic-tokenvalues |
editor | [{"field": "Sender.FullName", "inputname": "SenderID"}] |
Takes the sample value from the form input with that name, and updates the placeholders when the input changes or loses focus |
data-datafields-dynamic-displayvaluemap |
input | {"<input value>": "<display value>"} |
Maps the input's value to the text shown; a mapped value #altFieldName#OtherInput takes the value of input OtherInput instead |
data-onchangenotify |
any input | the name of a dynamic input |
A change here also refreshes the placeholders (for values that depend on two fields) |
For a <select> the selected option's text is used, unless a display value map is set. Dynamic values
only change what the editor shows; the saved HTML keeps the template tags.
Sample values are inserted into the editor as HTML. Escape plain-text values, as below, so a value
holding < or & shows as text:
use SilverStripe\Core\Convert; $values = []; foreach ($fields as $field) { # relField() follows dotted paths such as Contact.FirstName $value = $record->relField($field['field']); if ($value) { $values[] = ['field' => $field['field'], 'value' => Convert::raw2xml((string) $value)]; } } $editorField->setAttribute('data-datafields-static-tokenvalues', json_encode($values)); $editorField->setAttribute('data-datafields-dynamic-tokenvalues', json_encode([ ['field' => 'Sender.FullName', 'inputname' => 'SenderID'], ['field' => 'Appointment.Date', 'inputname' => 'Date'], ])); $locationDropdown->setAttribute( 'data-datafields-dynamic-displayvaluemap', json_encode($locations->map('ID', 'FullAddress')->toArray()) );
Using the plugin in a TinyMCE you initialise yourself
In the CMS, apply_datafields_base() is all that is needed: the editor config carries the plugin's URL.
A front end that calls tinymce.init() itself must pass that URL as an external plugin. Naming
datafields only in plugins makes TinyMCE look for plugins/datafields/plugin.min.js next to its own
files, which does not exist.
Pass the URL from PHP, for example as a data attribute:
$editorField->setAttribute('data-datafields-plugin', HTMLEditorConfigHelper::plugin_url()); $editorField->setAttribute('data-datafields', json_encode($fields));
and initialise TinyMCE 6 with it:
var textarea = document.querySelector('textarea.letter-body'); tinymce.init({ target: textarea, external_plugins: { datafields: textarea.getAttribute('data-datafields-plugin') }, toolbar: 'datafields', // the fields come from the data-datafields attribute, or from a datafields option here });
TinyMCE 6 has non-editable elements in its core: do not list noneditable in plugins (that plugin no
longer exists, and TinyMCE would fail to load it). If the field is a Silverstripe HTMLEditorField, its
data-config attribute already holds the complete editor config, external_plugins included:
tinymce.init(Object.assign(JSON.parse(textarea.dataset.config), { target: textarea })).
The dynamic values listen on the document through jQuery when the page has it (the CMS dropdowns announce changes with jQuery events), and with plain DOM listeners otherwise; neither is required.
Merge tags
apply_mergetags_base($config) adds a "Merge tags" dropdown that inserts the tag text as-is. Declare the
entries in the mergetags option (or a data-mergetags attribute):
| Key | Meaning |
|---|---|
tag |
Text to insert, eg {$Recipient.FirstName} |
label |
Label in the dropdown (default: tag) |
menu |
true starts a sub-menu titled label; the following entries go into it |
disabled |
Shows the entry greyed out |
Upgrading from 1.x
- Silverstripe 5.4 or 6 and PHP 8.1 are required; Silverstripe 4 stays on 1.x (branch
v1). HTMLEditorConfigHelperno longer extendsTinyMCEConfig(that class moved namespace in Silverstripe 6). Its static methods are unchanged; the apply methods now also return the config and take an optional toolbar position.apply_datafields_base()andapply_mergetags_base()no longer enable thenoneditableplugin: TinyMCE 6 has no such plugin.- The plugin scripts are rewritten for TinyMCE 6; the TinyMCE 3 and 4 code paths are gone. A
tinymce.init()of your own must useexternal_plugins(see above). - Dynamic values no longer special-case jQuery UI datepickers (
<name>Visibleinputs): Silverstripe 4 and later date fields are plain inputs.
Tests
- PHPUnit (
tests/): the helper (config copy, plugin and button wiring, the span rule). Run from a host project that requires the module, with thephpunit.xml.distin this repository as a template. - Playwright (
tests/browser/): the plugins in a real CMS edit form on Silverstripe 5 and 6: placeholders rendered from stored tags, insert from the toolbar, static and dynamic values, double-click to unwrap, non-editable behaviour, the saved HTML, merge tags. CI runs both on every push (.github/workflows/ci.yml).
Changelog
See CHANGELOG.md.
License
MIT, see LICENSE.
