Transformers
A transformer is a short JavaScript script attached to a content model. Plenary runs it every time an entry of that model is created or updated, after the request is parsed and before the values are validated and stored. A transformer can change the entry’s values (fill a slug, normalize a phone number, derive a label) or refuse the save with a message for the editor.
Transformers run inside the save. To react to a change after it is saved, for example to notify another system, use a webhook instead.
// Derive a display label from the numeric price.data.price_label = data.price === null ? 'Free' : `$${data.price.toFixed(2)}`When transformers run
Section titled “When transformers run”| Write | Transformers run |
|---|---|
Creating an entry (console or POST /api/v1/content/{model_key}) |
Yes, with ctx.operation = "create" |
Updating an entry (console or PUT /api/v1/content/{entry_id}) |
Yes, with ctx.operation = "update" |
| Restoring an entry from a revision | Yes: a revert runs as "update", an undelete as "create" |
| Publishing or unpublishing without editing | No |
| Form entries | No. Forms accept public input, and transformers do not run on it. |
Within one save:
- Text values are trimmed (for text fields with trimming on).
- Every active transformer runs, in the order listed on the model. Each one sees the previous one’s changes.
- Empty values are cleared, then the result is validated against the model’s fields and rules.
- The entry is stored, a revision is recorded, and webhooks are queued.
Because transformers run before validation, everything a transformer writes is held to the same rules as an editor’s input; a transformer cannot store a value the model would refuse. Its changes are simply part of the saved entry, so they appear in revision history and webhook payloads. Computed fields are rendered after validation, so a transformer reading a computed field sees its value from before this save.
Add a transformer in the console
Section titled “Add a transformer in the console”- Open the model’s Settings from Content and go to the Transformers tab.
- Click Add transformer, give it a Name, and write the Script.
- Leave Active on. A paused transformer is kept but does not run.
- Use Move up and Move down to put transformers in the order they should run, then click Save model.
The script is checked when you save the model. If it uses something the sandbox does not allow, the save is refused with the reason and the line and column, for example Transformer "Slug from title" is not valid: a regular expression is not available (line 1, column 36).
Managing transformers needs the content:transformers:manage capability, which can be scoped to one model. It is deliberately separate from the webhooks capability. Transformers are stored on the model, so every change to one is a model revision, and they are part of the model’s YAML file (transformers: [{ name, source, active }]); see Models as code.
Configure transformers through the API
Section titled “Configure transformers through the API”curl -X PUT https://your-instance.plenarycms.io/api/v1/models/MODEL_ID/transformers \ -H "Authorization: Bearer $PLENARY_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "transformers": [ { "name": "Price label", "source": "data.price_label = data.price === null ? \"Free\" : `$${data.price.toFixed(2)}`", "active": true } ] }'MODEL_ID is the model’s UUID. The array replaces the model’s transformers and sets their order. Include an existing transformer’s id to update it; omit id to create one. active defaults to true. The response returns the saved array, each item with id, name, event (always before_save), source, and active.
| Status | Code | Meaning |
|---|---|---|
| 422 | transformer_name_required |
A transformer has no name. vars.index |
| 422 | transformer_source_required |
A transformer has no script. vars.index, vars.name |
| 422 | transformer_source_invalid |
The script does not parse or uses something not allowed. vars.message includes the line and column. |
| 422 | transformer_not_found |
An id names no existing transformer. |
| 422 | transformer_duplicate |
The same id appears twice. |
What a script can read and change
Section titled “What a script can read and change”A script gets two variables:
| Name | Contents | Writable |
|---|---|---|
data |
The entry’s field values, keyed by field key. | Yes. Assign to data.<key> (or nested paths). |
ctx |
Read-only facts about the save. | No |
ctx contains:
| Property | Example | Description |
|---|---|---|
ctx.operation |
"create" |
"create" or "update". |
ctx.model |
"event" |
The model key. |
ctx.site_key |
"default" |
The site_key query parameter of the request, or "" if it was not sent. |
ctx.locale |
"en-us" |
The locale query parameter of the request, or "" if it was not sent. |
ctx.now |
"2026-10-07T09:15:46Z" |
The time of the save as an RFC 3339 UTC string, the same for every transformer in the save. |
ctx.actor |
{ "type": "user", "label": "editor@example.com" } |
Who is saving. type is user, api_key, or system. |
How values look in data:
- Every field the model declares is present, even if this entry has no value for it. Unset values are
null. Anobjectfield is always an object, sodata.address.cityreadsnullrather than throwing. Only a typo in a key givesundefined. - A
selectfield holds its stored value ("CO"), not its label ("Colorado"). datevalues are strings like"2026-11-01", so<and>compare them correctly.- Calling a method on a
nullvalue throws. Guard first:if (data.phone) { … }ordata.notes?.trim().
What gets saved: the submitted values plus any key the scripts changed. Setting a field the request did not include adds it. To clear a field, assign null.
The sandbox
Section titled “The sandbox”A transformer is plain JavaScript restricted to a fixed set of language features. The restriction is enforced when you save the model, by checking the script’s syntax tree against an allowlist, not at run time. A script that passes the check cannot reach anything outside data and ctx.
Allowed:
const,let,var;if/else;for,while,do…while;break,continue;return(to stop early);throw(to refuse the save).- Literals, template strings, array and object literals, arithmetic, comparison, logical and bitwise operators,
??,?.,typeof,in, the ternary operator,++/--on your own variables and ondata. - Calling these methods on any value:
toUpperCase,toLowerCase,trim,trimStart,trimEnd,substring,slice,charAt,charCodeAt,indexOf,lastIndexOf,includes,startsWith,endsWith,split,replace,replaceAll,repeat,padStart,padEnd,concat,at,toString,normalize,localeCompare,toFixed,toPrecision,join. Math.round,floor,ceil,abs,min,max,pow,sqrt,trunc,sign;JSON.stringify,JSON.parse;Number.isInteger,isFinite,isNaN,parseFloat,parseInt;String.fromCharCode;Array.isArray;undefined,NaN,Infinity.
Not allowed (refused when you save):
| Not available | Use instead |
|---|---|
Regular expressions (/…/, RegExp) |
includes, startsWith, endsWith, split, replaceAll, indexOf, or a character loop |
fetch, require, import, timers, any I/O |
A webhook for anything that calls another system |
Date, Math.random |
ctx.now for the current time |
Function declarations, arrow functions, class, new, this, eval |
Inline code; loops |
Calling anything except a listed method, such as Number(x) or String(x) |
Number.parseFloat(x), `${x}` or x.toString() |
try/catch |
Guard with if and ?. before the call that could fail |
switch, for…of, for…in, labels, the comma operator, destructuring, spread, getters and setters |
if/else if; an index-based for loop |
Array methods map, filter, reduce, forEach, push, pop, sort, reverse, splice |
A for loop that builds a new array with concat, then assign it |
Assigning to ctx or replacing data itself |
Assign to data.<key> |
The delete operator |
Assign null to clear a field |
constructor, prototype, __proto__ |
Why there are no regular expressions
Section titled “Why there are no regular expressions”The script engine hands any pattern it cannot compile natively to a backtracking matcher, and a running match cannot be interrupted by the time limit. One badly shaped pattern applied to a long value could hang the request indefinitely. Rather than let a single expression take down a save, the sandbox refuses regular expressions entirely. String methods and character loops cover the common cases, as the examples below show. (Field validation is separate: a text field’s regex validation rule is still available.)
Time limit
Section titled “Time limit”A transformer that is still running after 200 ms is stopped and the save is refused with entry_transformer_timeout. The limit is fixed. It exists to stop an accidental infinite loop from holding a request.
Refuse a save
Section titled “Refuse a save”throw a message to reject the save. Nothing is stored, later transformers do not run, and the editor sees your text:
if (data.starts && data.ends && data.ends < data.starts) { throw { field: 'ends', message: 'An event cannot end before it starts.' }}Throw either a non-empty string or an object with a string message and an optional field. With field, the console shows the message under that field. The API answers 422:
{ "error": { "code": "entry_transformer_rejected", "vars": { "field": "ends", "message": "An event cannot end before it starts.", "transformer": "Date order" } }}The message is sent exactly as written; Plenary does not translate it. Branch on ctx.locale if editors work in several languages. Transformers run before validation, so a rejection is reported before any ordinary field errors. A refusal applies to restores too: restoring an old revision that breaks a newer rule is refused the same way.
Errors editors can see
Section titled “Errors editors can see”| Code | When | vars |
|---|---|---|
entry_transformer_rejected |
The script threw a message on purpose. | transformer, message, optional field |
entry_transformer_failed |
The script crashed, for example by calling a method on null, or threw something that is not a message (throw 42). |
transformer, message, and line/column when known |
entry_transformer_timeout |
The script ran longer than 200 ms. | transformer, message |
All three are 422 and nothing is saved. A crash looks like this:
{ "error": { "code": "entry_transformer_failed", "vars": { "transformer": "Trim notes", "message": "TypeError: Cannot read property 'trim' of undefined or null", "line": 1, "column": 19 } }}In the console the editor sees The "Trim notes" transformer failed: …. A failing transformer blocks every save of that model until it is fixed or paused, so test new scripts on a draft entry.
Examples
Section titled “Examples”Each example below was run against a live instance. Field keys are placeholders for your own.
Slugify a title
Section titled “Slugify a title”Fills url_slug from title when the editor left it empty: lowercases, strips accents, and joins runs of letters and digits with single hyphens. " Café Résumé Night! " becomes "cafe-resume-night".
// Fill url_slug from the title when the editor left it empty.if (!data.url_slug && data.title) { const allowed = 'abcdefghijklmnopqrstuvwxyz0123456789' const source = data.title.toLowerCase().normalize('NFKD') let slug = '' let pendingDash = false for (let i = 0; i < source.length; i++) { const ch = source.charAt(i) if (ch >= '̀' && ch <= 'ͯ') continue // accent marks: drop them if (allowed.includes(ch)) { if (pendingDash && slug.length > 0) slug += '-' slug += ch pendingDash = false } else { pendingDash = true } } data.url_slug = slug}Normalize a phone number
Section titled “Normalize a phone number”Keeps only digits, accepts 10-digit US numbers with or without a leading 1, stores them in E.164 form, and refuses anything else under the field. "(303) 555-0142" becomes "+13035550142".
// Keep only digits, then store US numbers as +1XXXXXXXXXX.if (data.phone) { let digits = '' for (let i = 0; i < data.phone.length; i++) { const ch = data.phone.charAt(i) if ('0123456789'.includes(ch)) digits += ch } if (digits.length === 11 && digits.startsWith('1')) digits = digits.substring(1) if (digits.length !== 10) { throw { field: 'phone', message: 'Enter a 10-digit US phone number.' } } data.phone = `+1${digits}`}Compute a field
Section titled “Compute a field”Writes a display label from a number field. 12.5 becomes "$12.50"; an empty price becomes "Free".
// Derive a display label from the numeric price.data.price_label = data.price === null ? 'Free' : `$${data.price.toFixed(2)}`For a value that is purely a template of other fields, such as a title made of a first and last name, a computed field is simpler. Use a transformer when the value needs logic or must be validated like typed input.
Stamp new entries only
Section titled “Stamp new entries only”if (ctx.operation === 'create' && !data.received_on) { data.received_on = ctx.now.substring(0, 10) // "2026-10-07"}Conditional field visibility
Section titled “Conditional field visibility”The same sandbox powers conditional field visibility. On a field in the model editor, set Editor visibility to Visible on condition and write an expression in Show this field when. In the API and YAML, this is the field’s visible_when property:
data.event_type === 'online'A visibility condition differs from a transformer in three ways:
- It is a single expression that produces a value. It cannot assign, loop, or throw.
- It can read
databut notctx, because the console evaluates it while the editor types, without server context. Every field it reads must exist on the model; a condition naming an unknown field is refused when you save the model. - It has a 50 ms time limit.
The console hides the field while the condition is false, and the server reaches the same answer on save: a hidden field is exempt from required and from its validation rules, and keeps whatever value it already had. If a condition throws while the editor is typing, the field is shown.
Related
Section titled “Related”- Content models
- Fields
- Webhooks: react after a save
- Model YAML
- Errors