PPPHP

Client‑Side Utility Library – pp Object

The pp global object provides modern, lightweight utilities that work everywhere in the framework — AJAX requests, dialog boxes, form helpers, and common functions like debounce and deep clone. It is loaded automatically on every project SPA page.

Dependencies: SweetAlert2 gives pp.dialog its rich look. When it isn't on the page, every pp.dialog method degrades gracefully to a native browser dialog (or a tiny built-in toast), so pp.dialog is always safe to call.

Now in generated apps too. pp.js ships with every generated application, so your own client code — including Custom Button handlers and JS snippets — can use pp.dialog, pp.ajax and pp.util out of the box.

Objects at a glance

Everything the client API gives you, in one place. Pick the object for the job, then jump to its section for the full method list.

ObjectWhat it's for
Runner / pp.ctrlReach any field/control on the page by name — read/write, show/hide, style, validate. Works on add, edit, view, print, pdf, cards, custom.
Runner — gridThe list/card rows and the current selection — records, keys, cells.
Runner.detail()Master/Detail child grids — read, and write child cells two-way.
Runner.button()Page buttons — Save, Cancel, Add, Delete, bulk actions — hide / show / enable / disable.
pp.dialogDialogs: toast, confirm, prompt, alert (rich, with native fallback).
pp.ajax · pp.runServer: fetch JSON, or call a named PHP action.
pp.form · pp.valLower-level form value + validation helpers.
pp.utilUtilities: debounce, throttle, formatDate, escapeHtml, uuid…
pp.page · pp.record()The current page context (table, action, id) and record.
New to this? Jump straight to the Cookbook — a run of copy-ready examples from basic to advanced. Every example here also autocompletes in the Events editor.

Contents

Runner – Page Control Access

The Runner object (a single control is also reachable as pp.ctrl(field)) is a clean, chainable way to reach any field on a page by its database name — no hand-written DOM look-ups. It's ideal in event code such as Custom Button handlers. Every field carries a data-pp-field="<name>" hook, and plain [name] inputs are found as a fallback.

Get a control

var c = Runner.getControl('first_name');   // current page
// PHPRunner-style, scoped to a page container, is also accepted:
var c = Runner.getControl(pageId, 'first_name');

Control methods (all chainable)

MethodDoes
getValue() / setValue(v)Read / write the value (text, select, checkbox, radio, plugins). setValue fires change.
getText()The visible text (e.g. a select's option label).
clear() · focus()Empty the value · move focus to it.
show() / hide() / visible(bool)Show / hide the whole field, label included.
enable() / disable() · readonly(bool) · required(bool)Toggle input state.
addClass(c) / removeClass(c)Style the field wrapper.
label()The field's label text.
on(evt, fn) / onChange(fn)Attach an event listener.
setMessage(msg[, 'success']) / clearMessage()Show / clear an inline message under the field.
validate(rules) / invalid()Check {required, minlength, email, pattern}; shows the message and records the state. Returns true when valid.
reset()Restore the value the field had when the page loaded.
isReadonly()Is the control read-only right now?
watch(fn)Run fn(value, control) on every change — the reactive backbone behind compute()/link().
addStyle(css) / setStyle(css) · getDispElem()Inline-style the control · the raw input element.
exists()false for an unknown field — nothing throws.

Page-level shortcuts

MethodReturns / does
Runner.getControlValue(field)One value, without an intermediate variable.
Runner.setControlValue(field, v)Set one field's value.
Runner.getData()Every field as one object: { first_name:'…', email:'…' }.
Runner.setData({ … })Set many fields at once.
Runner.fields()Array of field names on the page.
Runner.hideField(f) / showField(f) / on(f, evt, fn)Field shortcuts.
Runner.getPageId() / getPageMode()The table this page edits / the page mode (add, edit, custom…).
// Chain freely — every method returns the control
Runner.getControl('email').setValue('').focus().setMessage('Enter a valid email');

// Read the whole form, guard, and light up the offending field
var d = Runner.getData();
if (!d.first_name) Runner.getControl('first_name').setMessage('Required').focus();
Familiar with PHPRunner? Runner.getControl(pageId, field) works the same way here — but the pageId is optional, so Runner.getControl(field) is all you usually need.

List / grid pages

On a list page, Runner reads the grid straight from the row data the build stamps on every row — the current selection, each row's record, and any cell — so a toolbar Custom Button can act on the ticked rows without any DOM work.

MethodReturns
Runner.getSelectedKeys()Ids of the ticked rows: ['1','4','7'].
Runner.getSelectedRecords()The ticked rows' records: [{ id, customer, total }, …].
Runner.selectedCount()How many rows are ticked.
Runner.getAllRecords()Every visible row's record.
Runner.rows() / getRow(id)Row object(s) — see below.
Runner.getCellValue(id, field)One cell's value for a given row.
Runner.onSelectionChange(fn)Fires with (keys, records) whenever the tick changes.
Runner.reloadGrid()Refresh the list (after a server change).

A row object (from rows() / getRow(id)) offers: .id, .data() (the whole record), .get('field'), .text('field') (visible cell text), .selected() / .select(true), .highlight(), .addClass(c), .on(evt, fn).

// A toolbar Custom Button that acts on the ticked rows
var ids = Runner.getSelectedKeys();
if (!ids.length) { pp.dialog.toast('warning', 'Select at least one row.'); return false; }
params.ids = ids;                        // ① Client Before → send to the server

// ② Server: dbExecute('UPDATE orders SET status=? WHERE id IN (' + …', …)
// ③ Client After:
Runner.reloadGrid();
The older pp.grid / pp.button.getSelectedRecords() helpers still work too — Runner is the newer, unified way, and both read the same row data.

Master / Detail

On a master's view or edit page, each child (detail) grid is its own grid object via Runner.detail('<detail_table>') — so you can read the children, the current child selection, and any child cell, right beside the master's own fields.

// The master's fields …
var orderRef = Runner.getControlValue('reference');

// … and its child rows, in the same breath
var items = Runner.detail('order_items').getAllRecords();       // [{ id, sku, qty, price }, …]
var total = items.reduce(function (s, it) { return s + it.qty * it.price; }, 0);
Runner.setControlValue('total', total);                         // write it back to the master

// Act on the ticked child rows
var picked = Runner.detail('order_items').getSelectedKeys();

// Every detail grid on the page
Runner.details().forEach(function (d) { console.log(d.table, d.grid.count()); });
CallReturns
Runner.detail(table)A grid object (same methods as the main grid) scoped to that child grid; .table, .fk, .exists().
.getAllRecords() / .getSelectedRecords()All / ticked child records.
.getSelectedKeys() / .count()Ticked child ids / row count.
.getCellValue(id, field) / .getRow(id)One child cell / one child row.
Runner.details()Every detail grid: [{ table, fk, grid }].

Editing child rows (two-way)

On an editable detail grid you can write a child cell in place and persist it — the change saves through the same permission-gated endpoint the app uses everywhere, so it respects each table's edit rights.

var d = Runner.detail('order_items');

// one cell → saved to the database (returns a Promise)
await d.setCellValue(itemId, 'qty', 5);

// several cells on one row, one save
await d.getRow(itemId).setValues({ qty: 3, price: 9.5 });

// recalculate every child and push a new price, then reload
for (const it of d.getAllRecords()) {
    await d.setCellValue(it.id, 'line_total', it.qty * it.price);
}
d.reload();
CallDoes
grid.setCellValue(id, field, value)Write one cell in place + save. Returns a Promise. (Works on the main grid too.)
row.setCell(field, value)Same, from a row object.
row.setValues({ … })Write several cells, one save.
row.set(field, value)Update the cell in the page only — no save (batch, then row.save()).
row.save([patch])Persist the whole row (or a patch).
grid.editCell(id, field)Open that cell's inline editor and focus it for the user (reuses the grid's own edit + autosave). Also Runner.editCell(id, field) on the main grid.
// "Add a row, then let the user type" — open the cell editor
Runner.editCell(newId, 'note');
// or on a detail grid
Runner.detail('order_items').editCell(itemId, 'qty');
Writes go through api/save.php — the signed-in user must have edit rights on that child table, and only real columns are saved. Reads work anywhere; writes need a table with real records behind it.

Read-only pages (View · Print · PDF · Cards)

There's nothing extra to learn: Runner.getControl('field') works on a View (and print / PDF) page too — with no input to type into, getValue() returns the field's displayed value. Card views behave like grid rows, so Runner.getAllRecords() reads the cards.

// On a View page — read what's shown
var name = Runner.getControl('full_name').getValue();
var when = Runner.getControl('created_at').getText();
One API, every page: add, edit, view, print, pdf, list, cards, custom, and Master/Detail. Read everywhere; write where the page has real inputs (add / edit).

Runner – page buttons

Reach a page button by name and hide / show / enable / disable it — or restyle it. A button object acts on every match, so Runner.button('edit') covers every row's Edit button at once.

Runner.button('save').disable();          // grey out Save
Runner.hideButton('deleteSelected');      // hide the bulk Delete
Runner.enableButton('save');
Runner.button('add').setText('New order');
Runner.button('cancel').addStyle('color:#dc2626');

// inside a Master/Detail child grid
Runner.detail('order_items').button('add').hide();
NameWhich button
addAdd New (list toolbar) or a detail grid's Add.
save · saveNew · saveCloseThe Add/Edit form's Save buttons.
cancel · back · resetThe form's Cancel / Back / Reset.
deleteSelected · editSelected · exportSelectedThe list's bulk-action buttons.
edit · delete · view · copyThe per-row action buttons (all rows).
MethodDoes
Runner.button(name)The button object. .exists(), .count().
.hide() / .show() / .visible(bool)Show or hide it.
.disable() / .enable()Grey it out / restore it (also works on links).
.setText(t) · .addStyle(css) · .addClass(c) · .on(evt, fn)Relabel, restyle, or wire it.
Runner.hideButton/showButton/disableButton/enableButton(name)One-line shortcuts.
Master/Detail tip. A common need: on a child (detail) record's page, hide the master-side Add or a bulk button when new children shouldn't be created — Runner.detail('items').button('add').hide(), or Runner.hideButton('deleteSelected').

pp.ajax – HTTP Requests

Thin wrappers around the Fetch API with built‑in JSON handling and a loading spinner helper.

GET request

const users = await pp.ajax.get('/api/users');

POST request (JSON)

const result = await pp.ajax.post('/api/save', {
    name: 'Alice',
    email: 'alice@example.com'
});
console.log(result.success); // true/false

File upload with progress

const formData = new FormData();
formData.append('file', fileInput.files[0]);

const response = await pp.ajax.upload('/api/upload', formData, (percent) => {
    console.log(`Uploading: ${percent}%`);
});

GET with automatic loading spinner

const data = await pp.ajax.load('/api/slow-endpoint', 'Fetching records…');
// Shows a SweetAlert2 spinner while loading, then auto‑closes

Adding custom headers

const data = await pp.ajax.get('/api/secure', {
    headers: { 'X-CSRF-Token': csrfToken }
});

pp.dialog – User Dialogs

Unified SweetAlert2 shortcuts that keep every module's UI consistent.

Toast notification

pp.dialog.toast('success', 'Record saved!');
pp.dialog.toast('error', 'Something went wrong.');
pp.dialog.toast('warning', 'Please check your input.');
pp.dialog.toast('info', '3 new notifications.');

Confirmation dialog

const confirmed = await pp.dialog.confirm(
    'Delete this record?',
    'This action cannot be undone.'
);
if (confirmed) {
    // proceed with deletion
}

Custom confirmation buttons

const yes = await pp.dialog.confirm('Archive?', 'Move to archive.', {
    confirmText: 'Archive',
    cancelText: 'Keep',
    confirmColor: '#0d6efd'
});

Text prompt

const folderName = await pp.dialog.prompt('New folder', 'Enter folder name');
if (folderName) {
    // create folder
}

Simple alert

await pp.dialog.alert('Done', 'All files processed.', 'success');

pp.form – Form Utilities

Quick value access and simple validation without heavyweight plugins.

Get / Set a form value

const email = pp.form.getValue('#email');
pp.form.setValue('#name', 'John Doe');

Checkbox and radio

const active = pp.form.getValue('#activeCheckbox');  // true/false
pp.form.setValue('#activeCheckbox', true);

const plan = pp.form.getValue('input[name="plan"]');  // 'basic'
pp.form.setValue('input[name="plan"]', 'premium');

Validate a field

const { valid, message } = pp.form.validate('#email', {
    required: true,
    email: true,
    requiredMessage: 'Email is required.'
});
if (!valid) {
    pp.dialog.toast('error', message);
}

Validate with minlength and pattern

const check = pp.form.validate('#username', {
    required: true,
    minlength: 3,
    pattern: /^[a-zA-Z0-9_]+$/,
    patternMessage: 'Only letters, numbers, and underscores allowed.'
});

Serialise a form to an object

const data = pp.form.toObject('#myForm');
// { name: "Alice", email: "alice@example.com", subscribe: "on" }
await pp.ajax.post('/api/submit', data);

pp.util – General Helpers

Debounce (search input)

const doSearch = pp.util.debounce((query) => {
    fetch(`/api/search?q=${query}`).then(res => res.json()).then(renderResults);
}, 400);

document.getElementById('searchBox').addEventListener('input', (e) => {
    doSearch(e.target.value);
});

Throttle (scroll handler)

window.addEventListener('scroll', pp.util.throttle(() => {
    console.log('User is scrolling...');
}, 200));

Format a date

pp.util.formatDate('2025-06-15');                      // "Jun 15, 2025, 12:00 am"
pp.util.formatDate('2025-06-15', 'F j, Y');            // "June 15, 2025"
pp.util.formatDate('2025-06-15 14:30:00', 'H:i');       // "14:30"

Deep clone an object

const original = { a: 1, b: { c: 2 } };
const copy = pp.util.deepClone(original);
copy.b.c = 99;
console.log(original.b.c);  // 2  (unchanged)

Generate a UUID

const id = pp.util.uuid();  // "c9b5a2e4-1234-4abc-5678-def012345678"

Escape HTML

const safe = pp.util.escapeHtml('<script>alert("xss")</script>');
// "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"

Reactive fields, page elements & rich dialogs

Higher-level helpers that turn common multi-line patterns into one line. They pair especially well with a field's On Change, a page's On Load, and Custom Button handlers.

Live calculated fields — Runner.compute()

Keep a field in sync with others. The function receives each dependency's value and returns the target's value; it re-runs the instant any dependency changes — no event wiring, no boilerplate.

// line_total = qty × price, always up to date
Runner.compute('line_total', ['qty', 'price'], function (qty, price) {
    return (+qty || 0) * (+price || 0);
});

// A grand total that follows several inputs
Runner.compute('grand_total', ['subtotal', 'tax', 'shipping'], (s, t, sh) =>
    (+s || 0) + (+t || 0) + (+sh || 0));

Mirror one field into another — Runner.link()

// Auto-slug a title as the user types
Runner.link('title', 'slug', v => v.toLowerCase().trim().replace(/\s+/g, '-'));

// Copy without transforming
Runner.link('billing_city', 'shipping_city');

Validate a field on the spot

var ok = Runner.getControl('email').validate({ email: true });
// shows the inline message + marks the field; returns false if invalid
if (!ok) return false;               // e.g. in Before Form Submit / Custom Button Client Before

Runner.getControl('name').reset();   // put a field back to its load-time value

Show / hide any element by id — Runner.item()

For headings, panels or custom HTML blocks you gave an id (PHPRunner's findItem/toggleItem).

// Reveal a legal notice only for US customers
Runner.getControl('country').watch(function (c) {
    Runner.item('us_legal').toggle(c === 'US');
});

Runner.item('summary').html('' + Runner.getControlValue('name') + '');

Drive tabs — Runner.getTabs()

Runner.getTabs().activate(2);                 // open the third tab of the first group
Runner.getTabs(0).activateByText('Billing');  // …or by its label

Warn about unsaved changes — Runner.setPageModified()

// Arm the browser's "leave page?" prompt when anything changes
Runner.fields().forEach(function (f) {
    Runner.getControl(f).watch(() => Runner.setPageModified(true));
});
// …then disarm after a successful save:
Runner.setPageModified(false);

Grid maths & selection in one call

On a list page use Runner.grid(); on a Master/Detail child grid use Runner.detail('table') — both expose the same conveniences.

var d = Runner.detail('order_items');
d.sum('line_total');                    // total a column — no loop
d.avg('price');                         // average
d.pluck('sku');                         // ['A-1','A-2', …]
d.filter(r => r.status === 'open');     // records matching a predicate
d.find(r => r.sku === 'A-1');           // first match (or null)
d.each(row => row.highlight());         // iterate row objects

d.selectWhere(r => r.overdue);          // tick rows by predicate
d.selectAll();  d.clearSelection();     // tick all / clear

Per-row messages

var row = Runner.grid().getRow(id);
row.setMessage('qty', 'Above available stock', 'error');   // inline, in that cell
row.clearMessage('qty');

Collect several values at once — pp.dialog.form()

A multi-field dialog (PHPRunner's ctrl.dialog({fields})). Resolves to { name: value } on OK, or null on Cancel. Perfect just before a Custom Button's server stage.

var v = await pp.dialog.form({
    title: 'Email the results',
    header: 'Where should we send it?',
    fields: [
        { name: 'email',   label: 'Email address', type: 'email', value: 'me@example.com' },
        { name: 'subject', label: 'Subject',       value: 'Your results' },
        { name: 'format',  label: 'Format', options: ['PDF', 'CSV'] },
        { name: 'copyme',  label: 'Send me a copy', type: 'checkbox', value: true },
    ],
    ok: 'Send',
});
if (!v) return false;             // user cancelled
params.email = v.email;           // …hand it to the Server stage
params.subject = v.subject;

Drive the list page's Quick Search from code, or filter the loaded rows instantly with no server round-trip.

var s = Runner.search();          // also Runner.getSearchController()
s.submit('ada');                  // server-side search (navigates with ?search=…)
s.getValue();  s.isSearched();    // read the box / is the list filtered?
s.clear();                        // back to the full, unfiltered list

// Instant client-side filter — hide non-matching rows, no fetch:
Runner.getControl('quickfind').watch(v => Runner.search().filterRows(v, ['name','email']));
Runner.search().clearFilter();

// Additional WHERE tabs:
Runner.search().whereTab(1);      // switch to a filter tab; allData() = All data
Runner.search().whereTabs();      // [{ index, label, active }]

Let the server drive the page — Runner.apply()

When PHP uses the pp() command bus (pp()->toast()->setControl()->reloadGrid()), those commands are applied in the browser by Runner.apply() — automatically after pp.run() and a Custom Button's server stage, so you usually write no client-after code. You can also apply a command list yourself:

Runner.apply([
    { cmd: 'setControl', field: 'status', value: 'approved' },
    { cmd: 'toast', type: 'success', message: 'Done' },
    { cmd: 'reloadGrid' },
]);

Cookbook — basic to advanced

A guided run of copy-ready recipes. They live in event code — a Custom Button, a field's On-Change, or a page's On-Load — and every one of them autocompletes in the Events editor.

Basics

1 · Make a field red on the View page

The classic first example — highlight a value so it can't be missed.

var ctrl = Runner.getControl('status');
ctrl.addStyle('color: red; font-weight: 700');

2 · Read and write a field

var email = Runner.getControlValue('email');        // read
Runner.setControlValue('username', email.split('@')[0]);   // write (fires change)

3 · Ask for confirmation before saving

In a Custom Button's Client Before, or a form's before-submit event:

if (!await pp.dialog.confirm('Submit this order?', 'You can’t edit it afterwards.')) {
    return false;   // cancels the action / stops the submit
}

4 · Toast instead of alert

pp.dialog.toast('success', 'Saved.');
pp.dialog.toast('warning', 'Nothing selected.');

Everyday

5 · Show or hide a field based on another

Put this in the type field's On-Change event so a VAT box only shows for companies:

Runner.getControl('type').onChange(function () {
    Runner.getControl('vat_number').visible(Runner.getControlValue('type') === 'company');
});

6 · Calculate a total on the fly

function recalc() {
    var qty   = +Runner.getControlValue('qty')   || 0;
    var price = +Runner.getControlValue('price') || 0;
    Runner.setControlValue('total', (qty * price).toFixed(2));
}
Runner.getControl('qty').onChange(recalc);
Runner.getControl('price').onChange(recalc);

7 · Enable / disable a button

Runner.disableButton('save');                         // grey out Save
Runner.getControl('agree').onChange(function () {     // enable it only when a box is ticked
    Runner.button('save')[Runner.getControlValue('agree') ? 'enable' : 'disable']();
});

8 · Hide the bulk “Delete selected” / “Edit selected” buttons

Runner.hideButton('deleteSelected');
Runner.hideButton('editSelected');

9 · Change the font / size of a control

Runner.getControl('notes').addStyle('font-size: 16px; font-family: Georgia, serif');

10 · Validate before submit, and message the field

var email = Runner.getControlValue('email');
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
    Runner.getControl('email').setMessage('Enter a valid email').focus();
    return false;
}
Runner.getControl('email').clearMessage();

Advanced

11 · Autofill from the server (AJAX)

Look a value up on the server and drop the answer into another field — no page reload:

Runner.getControl('email').onChange(async function () {
    var contact = await pp.run('findContact', { email: Runner.getControlValue('email') });
    if (contact) Runner.setData({ full_name: contact.name, phone: contact.phone });
});
// (server side: define action_findContact($params) in Custom Functions → PHP)

12 · Bulk action on the selected list rows

var ids = Runner.getSelectedKeys();
if (!ids.length) { pp.dialog.toast('info', 'Select at least one row.'); return false; }
await pp.run('markShipped', { ids: ids });
Runner.reloadGrid();

13 · Master/Detail — total the child rows onto the master

var items = Runner.detail('order_items').getAllRecords();
var total = items.reduce(function (s, it) { return s + (+it.qty) * (+it.price); }, 0);
Runner.setControlValue('total', total);

14 · Master/Detail — hide Add when the record is locked

On the master's Edit page (a page On-Load event), stop new children being added to a closed order:

if (Runner.getControlValue('status') === 'closed') {
    Runner.detail('order_items').button('add').hide();
    Runner.hideButton('deleteSelected');
}

15 · Edit a child cell, and save it

var d = Runner.detail('order_items');
await d.setCellValue(itemId, 'qty', 5);          // write + persist one cell
await d.getRow(itemId).setValues({ qty: 3, price: 9.5 });   // several, one save
Runner.editCell(newRowId, 'sku');                // or open the cell editor for the user

16 · Refresh the List page after editing in a popup

// In the popup's after-save event (or a Custom Button's Client After):
if (window.parent && window.parent !== window) window.parent.location.reload();
else Runner.reloadGrid();

Going further

17 · Focus the first field when an Add form opens

A small polish that saves the user a click. Put it in the page's On-Load event.

if (Runner.getPageMode() === 'add') {
    Runner.getControl(Runner.fields()[0]).focus();   // first field on the page
}

18 · Format a currency field as the user types

on('input', …) reacts to every keystroke; pp.util keeps it tidy.

Runner.getControl('amount').on('blur', function () {
    var n = parseFloat(String(Runner.getControlValue('amount')).replace(/[^0-9.]/g, '')) || 0;
    Runner.setControlValue('amount', n.toFixed(2));
});

19 · Cascading lookups — filter a child list by the parent

When country changes, reload city options from the server (via a named action).

Runner.getControl('country').onChange(async function () {
    var cities = await pp.run('citiesFor', { country: Runner.getControlValue('country') });
    var sel = Runner.getControl('city').el;   // the <select> element
    if (sel) sel.innerHTML = cities.map(function (c) { return '<option>' + pp.util.escapeHtml(c) + '</option>'; }).join('');
});

20 · Confirm a delete showing the record's name

Attach to the row Delete buttons and read the row's own record for a friendlier prompt.

Runner.rows().forEach(function (row) {
    row.tr.querySelector('.ppd-action-delete')?.addEventListener('click', async function (e) {
        e.preventDefault(); e.stopPropagation();
        if (await pp.dialog.confirm('Delete “' + row.get('name') + '”?', 'This cannot be undone.')) {
            await pp.run('deleteRecord', { id: row.id }); Runner.reloadGrid();
        }
    }, true);
});

21 · Block save when a detail grid is empty

In a Custom Button's Client Before, or a before-submit event on the master:

if (Runner.detail('order_items').count() === 0) {
    pp.dialog.toast('warning', 'Add at least one line item first.');
    return false;
}

22 · Sum a grid column and show it

var total = Runner.getAllRecords().reduce(function (s, r) { return s + (+r.amount || 0); }, 0);
pp.dialog.toast('info', 'Total on this page: ' + total.toFixed(2));

23 · Highlight grid rows that match a condition

Runner.rows().forEach(function (row) {
    if ((+row.get('balance') || 0) < 0) row.highlight('rgba(220,38,38,.12)');
});

24 · Live server-side uniqueness check

Debounced so it only asks the server when the user pauses typing.

var check = pp.util.debounce(async function () {
    var ok = await pp.run('emailAvailable', { email: Runner.getControlValue('email') });
    Runner.getControl('email').setMessage(ok ? '' : 'Already registered', ok ? 'success' : 'error');
}, 400);
Runner.getControl('email').on('input', check);

25 · Copy a master value into every child row, then save

var currency = Runner.getControlValue('currency');
var d = Runner.detail('order_items');
for (var it of d.getAllRecords()) { await d.setCellValue(it.id, 'currency', currency); }
d.reload();

26 · Warn before leaving with unsaved changes

var dirty = false;
Runner.fields().forEach(function (f) { Runner.getControl(f).on('input', function () { dirty = true; }); });
window.addEventListener('beforeunload', function (e) { if (dirty) { e.preventDefault(); e.returnValue = ''; } });

27 · Save with Ctrl/Cmd + S

document.addEventListener('keydown', function (e) {
    if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
        e.preventDefault(); Runner.button('save').els[0]?.click();
    }
});

28 · Read the current record / URL context

var id   = pp.page.id;          // the record id from the URL
var mode = Runner.getPageMode();  // 'add' | 'edit' | 'view' | 'custom'
var rec  = pp.record();          // the whole record on view/edit (may be null)

29 · Lock the whole form to read-only

Runner.fields().forEach(function (f) { Runner.getControl(f).readonly(true); });
Runner.button('save').hide();

30 · Poll a value and update a field live

setInterval(async function () {
    var n = await pp.run('pendingCount', {});
    Runner.getControl('pending').setValue(n);
}, 15000);   // every 15s

More real‑world examples

Example 1 – Save form with loading spinner

async function saveRecord() {
    const data = pp.form.toObject('#recordForm');
    const result = await pp.ajax.load('/api/save', 'Saving…', {
        method: 'POST',
        body: JSON.stringify(data)
    });
    if (result.success) {
        pp.dialog.toast('success', 'Record saved!');
    } else {
        pp.dialog.toast('error', result.message);
    }
}

Example 2 – Delete with confirmation

async function deleteRecord(id) {
    const ok = await pp.dialog.confirm('Delete?', 'Record #' + id + ' will be permanently removed.');
    if (!ok) return;

    const result = await pp.ajax.post('/api/delete', { id });
    if (result.success) {
        pp.dialog.toast('success', 'Deleted.');
    }
}

Example 3 – Live search with debounce

const search = pp.util.debounce(async (query) => {
    const results = await pp.ajax.get(`/api/search?q=${encodeURIComponent(query)}`);
    renderResults(results);
}, 300);

document.getElementById('searchInput').addEventListener('input', e => search(e.target.value));

Example 4 – Form validation before submit

document.getElementById('saveBtn').addEventListener('click', async () => {
    const emailCheck = pp.form.validate('#email', { required: true, email: true });
    const nameCheck  = pp.form.validate('#name', { required: true, minlength: 2 });

    if (!emailCheck.valid) return pp.dialog.toast('error', emailCheck.message);
    if (!nameCheck.valid)  return pp.dialog.toast('error', nameCheck.message);

    // All good – submit
    await pp.ajax.post('/api/save', pp.form.toObject('#myForm'));
    pp.dialog.toast('success', 'Saved!');
});

🔗 Related Help Topics

Database API Security API Search API