Skip to content

Virtual fields ​

Some data edited with a record has no column of its own and does not fit a repeater: a question's answers, a category's highlights, a product's variants, whose shape and rules depend on other fields. A virtual field is a field of the record's form without a column:

  • an extension draws it in React (React pages, SDK ui 6), with the form's other values as they are being edited;
  • the application stores it in its own tables, in a handler the panel calls inside the record's save: one form, one save button, one transaction;
  • the panel keeps its rules: who may read and write it, conditions, rich text and media checks, errors under the part that caused them, the audit log.

The demo's category form: its highlights, a virtual field drawn by the demo's React extension

Virtual field or relationship repeater ​

Prefer a relationship repeater when the data is rows of a registered resource with fixed inputs: the panel draws them, and each row keeps the child's policy, scope, hooks and audit. Reach for a virtual field when one of these holds:

  • its shape changes with another field (a single-choice question's choices, a fill-in question's blanks);
  • its rules span rows and the record ("exactly one correct answer");
  • it nests (blanks, each with its accepted answers), which relationship rows cannot;
  • it is not a resource of its own and should not become one;
  • it needs an editor of its own (drag a blank into the prompt).

The price: you write validate and save yourself, including the check that ids sent back belong to this record (below), and the field is never listed, filtered or imported.

Quick start ​

  1. Write the handler: how the field loads, checks, saves and deletes.
rs
use rustcms::AppResult;
use rustcms::admin::*;
use sea_orm::prelude::Uuid;
use sea_orm::{
    ActiveModelTrait, ActiveValue::Set, ColumnTrait, DatabaseTransaction, EntityTrait, QueryFilter, QueryOrder,
};
use serde_json::{Value, json};

use crate::admin::resources::category_resource::CategoryResource;
use crate::models::{category, category_highlight as highlight};

/// Most highlights of a category, and the longest title.
const MAX_ITEMS: usize = 6;
const MAX_TITLE: usize = 120;

pub struct Highlights;

#[async_trait::async_trait]
impl VirtualField for Highlights {
    type Resource = CategoryResource;
    const NAME: &'static str = "highlights";
    const WIDGET: &'static str = "demo/highlights";

    /// `[{id, title, text, image}]`, in order.
    async fn load(_ctx: &Ctx, txn: &DatabaseTransaction, record: &category::Model) -> AppResult<Value> {
        let rows = highlight::Entity::find()
            .filter(highlight::Column::CategoryId.eq(record.id))
            .order_by_asc(highlight::Column::Position)
            .all(txn)
            .await?;
        Ok(Value::Array(
            rows.into_iter().map(|h| json!({"id": h.id, "title": h.title, "text": h.text, "image": h.image})).collect(),
        ))
    }

    fn initial(_ctx: &Ctx) -> Value {
        json!([])
    }

    async fn validate(
        _ctx: &Ctx,
        txn: &DatabaseTransaction,
        value: Value,
        _written: &Data,
        stored: Option<&category::Model>,
        check: &mut Checker,
    ) -> AppResult<Value> {
        let items = match value {
            Value::Null => Vec::new(),
            Value::Array(items) => items,
            _ => {
                check.error("", "is invalid");
                return Ok(Value::Null);
            }
        };
        if items.len() > MAX_ITEMS {
            // Refused before anything else: a long list is never walked.
            check.error("", format!("may not have more than {MAX_ITEMS} items"));
            return Ok(Value::Null);
        }
        // Ids are the rows of this category only (anything else is refused).
        let own: Vec<i32> = match stored {
            Some(category) => highlight::Entity::find()
                .filter(highlight::Column::CategoryId.eq(category.id))
                .all(txn)
                .await?
                .into_iter()
                .map(|h| h.id)
                .collect(),
            None => Vec::new(),
        };
        let mut out = Vec::with_capacity(items.len());
        let mut used = Vec::new();
        for (i, item) in items.iter().enumerate() {
            let id = item.get("id").filter(|id| !id.is_null());
            if let Some(id) = id {
                // A row of this category, named once.
                match id.as_i64().and_then(|id| i32::try_from(id).ok()) {
                    Some(id) if own.contains(&id) && !used.contains(&id) => used.push(id),
                    _ => check.error(&format!("{i}.id"), "is invalid"),
                }
            }
            let title = item["title"].as_str().unwrap_or_default().trim();
            if title.is_empty() {
                check.error(&format!("{i}.title"), "is required");
            } else if title.chars().count() > MAX_TITLE {
                check.error(&format!("{i}.title"), format!("may not be longer than {MAX_TITLE} characters"));
            }
            // Rich text through the core's parser; images through its media check.
            let text = check.rich_text(&format!("{i}.text"), &item["text"]).unwrap_or(Value::Null);
            let image = match item.get("image").filter(|v| !v.is_null()) {
                None => None,
                Some(v) => match v.as_str().and_then(|s| Uuid::parse_str(s).ok()) {
                    Some(image) => {
                        check.media(&format!("{i}.image"), &[image], &["image/*"], None);
                        Some(image)
                    }
                    None => {
                        check.error(&format!("{i}.image"), "is invalid");
                        None
                    }
                },
            };
            out.push(json!({"id": id, "title": title, "text": text, "image": image}));
        }
        Ok(Value::Array(out))
    }

    /// Replaces the category's highlights by `value`: rows named by id are
    /// updated, others inserted, the rest deleted.
    async fn save(_ctx: &Ctx, txn: &DatabaseTransaction, record: &category::Model, value: Value) -> AppResult<()> {
        let items = value.as_array().cloned().unwrap_or_default();
        let kept: Vec<i32> =
            items.iter().filter_map(|i| i["id"].as_i64().and_then(|id| i32::try_from(id).ok())).collect();
        highlight::Entity::delete_many()
            .filter(highlight::Column::CategoryId.eq(record.id))
            .filter(highlight::Column::Id.is_not_in(kept))
            .exec(txn)
            .await?;
        for (position, item) in items.iter().enumerate() {
            let mut row = highlight::ActiveModel {
                category_id: Set(record.id),
                position: Set(position as i32),
                title: Set(item["title"].as_str().unwrap_or_default().to_owned()),
                text: Set(item.get("text").filter(|t| !t.is_null()).cloned()),
                image: Set(item["image"].as_str().and_then(|s| Uuid::parse_str(s).ok())),
                ..Default::default()
            };
            match item["id"].as_i64().and_then(|id| i32::try_from(id).ok()) {
                Some(id) => {
                    row.id = Set(id);
                    row.update(txn).await?;
                }
                None => {
                    row.insert(txn).await?;
                }
            }
        }
        Ok(())
    }
}
  1. Declare it on the resource, and place it in the form:
rs
fn virtual_fields() -> Vec<Virtual<Self>> {
    vec![
        Virtual::of::<crate::admin::fields::category_highlights::Highlights>()
            .label("Highlights")
            .collection("post-content"),
    ]
}
rs
// A virtual field (ADR 0046): drawn by `registerField("demo/highlights")`,
// saved with the category (`admin/fields/category_highlights.rs`).
VirtualInput::make("highlights")
    .help("Up to 6, shown at the top of the category's page")
    .shown_when(when("layout").eq("posts")),
  1. Draw it in an extension (registerField):
tsx
type Highlight = { id?: number | null; key?: string; title: string; text: RichDocument | null; image: string | null };

/** Rows get a key of their own (stored ones: their id), so moving them keeps each editor with its row. */
const keyOf = (h: Highlight, i: number) => h.key ?? (h.id != null ? `id-${h.id}` : `row-${i}`);

/**
 * A category's highlights (a virtual field, level 6): rows of a title, a
 * short text and an image, drawn with the forms' parts. The heading follows
 * the category's name as it is typed; the server's errors land under each
 * part; `onBusy` holds the save while an image uploads.
 */
function HighlightsEdit(props: FieldProps<Highlight[], { name?: string }>) {
  const items = (props.value ?? []) as Highlight[];
  const busy = useRef(new Set<string>());
  const set = (next: Highlight[]) => props.onChange(next);
  const update = (i: number, patch: Partial<Highlight>) => set(items.map((h, j) => (j === i ? { ...h, ...patch } : h)));
  const move = (from: number, to: number) => {
    const next = [...items];
    next.splice(to, 0, next.splice(from, 1)[0]!);
    set(next);
  };
  const report = (key: string) => (on: boolean) => {
    if (on) busy.current.add(key);
    else busy.current.delete(key);
    props.onBusy(busy.current.size > 0);
  };
  return (
    <div className="demo-highlights" id={props.id} aria-describedby={props.describedBy}>
      <p className="demo-highlights-heading">
        {props.t("Highlights of")} {props.values.name?.trim() || props.t("this category")}
      </p>
      {props.errors[""] && <FieldError>{props.errors[""]}</FieldError>}
      <ol className="demo-options">
        {items.map((h, i) => {
          const key = keyOf(h, i);
          const at = `${props.id}-${key}`;
          return (
            <li key={key}>
              <RepeaterRow
                title={`${i + 1}. ${h.title || props.t("Untitled")}`}
                invalid={Object.keys(props.errors).some((p) => p.startsWith(`${i}.`))}
                onMoveUp={props.disabled ? undefined : i > 0 ? () => move(i, i - 1) : null}
                onMoveDown={props.disabled ? undefined : i < items.length - 1 ? () => move(i, i + 1) : null}
                onRemove={props.disabled ? undefined : () => set(items.filter((_, j) => j !== i))}
              >
                <FormField id={`${at}-title`} label={props.t("Title")} error={props.errors[`${i}.title`]} required>
                  {(aria) => (
                    <Input id={`${at}-title`} value={h.title} disabled={props.disabled} {...aria}
                      onChange={(e) => update(i, { title: e.target.value })} />
                  )}
                </FormField>
                <FormField id={`${at}-image`} label={props.t("Image")} error={props.errors[`${i}.image`]}>
                  {(aria) => (
                    <MediaField id={`${at}-image`} label={props.t("Image")} value={h.image}
                      rules={{ accept: ["image/*"], collection: props.collection }} disabled={props.disabled}
                      invalid={!!aria["aria-invalid"]} describedBy={aria["aria-describedby"]} onBusy={report(`${key}-image`)}
                      onChange={(image) => update(i, { image: typeof image === "string" ? image : null })} />
                  )}
                </FormField>
                <FormField id={`${at}-text`} label={props.t("Text")} error={props.errors[`${i}.text`]} className="md:col-span-2">
                  {(aria) => (
                    <RichEditor id={`${at}-text`} label={props.t("Text")} value={h.text} toolbar="compact"
                      field={{ resource: "categories", name: "highlights" }} disabled={props.disabled}
                      invalid={!!aria["aria-invalid"]} describedBy={aria["aria-describedby"]} onBusy={report(`${key}-text`)}
                      onChange={(text) => update(i, { text })} />
                  )}
                </FormField>
              </RepeaterRow>
            </li>
          );
        })}
      </ol>
      {!props.disabled && (
        <Button variant="outline" disabled={items.length >= 6}
          onClick={() => set([...items, { key: crypto.randomUUID(), title: "", text: null, image: null }])}>
          {props.t("Add a highlight")}
        </Button>
      )}
    </div>
  );
}

/** On the category's view page: the titles and texts. */
function HighlightsView(props: FieldProps<Highlight[]>) {
  const items = (props.value ?? []) as Highlight[];
  if (items.length === 0) return <p className="demo-muted">{props.t("No highlights")}</p>;
  return (
    <ol className="demo-options">
      {items.map((h, i) => (
        <li key={keyOf(h, i)}>
          <strong>{h.title}</strong>
          {h.text && <RichTextView doc={h.text} />}
        </li>
      ))}
    </ol>
  );
}

registerField<Highlight[], { name?: string }>("demo/highlights", { edit: HighlightsEdit, view: HighlightsView });

/** On the category's view page (its infolist): the same list. */
function HighlightsEntry(props: EntryProps<Highlight[] | null>) {
  return <HighlightsView {...({ value: props.value, t: props.t } as unknown as FieldProps<Highlight[]>)} />;
}
registerEntry("demo/highlights", HighlightsEntry);

The demo's category form shows it under its posts; its view page draws it with a CustomEntry of the same name.

The handler ​

VirtualField is implemented once per field:

ItemWhat it does
NAMEthe input's name ([a-z][a-z0-9_]*, 64 at most), unique among the resource's fields, relations and inputs
WIDGETthe extension's field, vendor/name (registerField)
DEPENDS_ONfields of the resource (its columns, checked at boot) whose change re-checks the stored value when the field is not sent (below)
load(ctx, txn, record)the value the form opens with, read from your tables
initial(ctx)the value a create form starts with (default null)
validate(ctx, txn, value, written, stored, check)checks a value against the record as this save wrote it (written: every column, hooks applied, column defaults filled in, encrypted columns as null) and as it was before (stored, None on create); returns the value save receives. It only reads: no row locks
save(ctx, txn, record, value)writes it: insert, update, delete
delete(ctx, txn, record)removes what save stored when the record is deleted for good (default: nothing, your foreign keys cascade)

Virtual::of::<H>() declares it in Resource::virtual_fields(), with .label(..), .readable(..), .creatable(..), .updatable(..), .required() (a value that is not null), .audit_redact(), .rich_nodes([..]) (the application elements its rich text may hold) and .collection(..) (where its files go). VirtualInput::make(name) places it in the form, with .label(..) (default: the declaration's), .help(..), .column_span(..) and .shown_when(..) (its widget and rules belong to the declaration: VirtualInput takes no .required(), options or bounds). Every declared virtual field is placed once; a generated form places them at its end.

Checking ​

validate reports through check (a Checker), so the panel keeps its own rules:

  • check.error(path, message): an error under name.path (highlights.1.title); "" for the field itself. Use the panel's messages (is required, is invalid, may not have more than {max} items, …) to have them translated.
  • check.rich_text(path, &value): the document checked by the panel's parser with the field's rich_nodes (closed schema, bounds); returns the document to store (in the lowest version it needs, defaults filled in), its images joining the media check. Store what it returns, never the document as sent.
  • check.media(path, &ids, accept, max_size): files checked with the record's at the end of the save: the user may see them, of an accepted type and size.

Ids are input. A value that names rows to update or delete (an answer's id) comes from the user: match each one against rows of this record and refuse the others, as the demo does. Otherwise a user who may edit one record could rewrite another's rows.

When it runs ​

In a create or an update:

  1. the virtual fields leave the input before the columns are checked (one the user may not write is refused at once, is not allowed); the columns, rows and conditions are then checked, and a field its conditions hide (as the user's form evaluates them) is dropped;
  2. mutate_before_*; the record, its links and its repeater rows are written;
  3. validate of each field sent, against the record as written (column defaults included); errors come back with a 422 and roll the write back (a request with bad columns and a bad virtual value answers the columns first);
  4. save, in the same transaction, under the record's lock;
  5. the media check, after_save, the audit log, commit. An error anywhere rolls everything back, your rows included.

validate and load only read your tables: they never lock rows (SELECT … FOR UPDATE), which could wait on locks the save takes later in another order than every other write. Only save writes.

A field not sent is left as it is. When a field in DEPENDS_ON changes (by the request or a hook), or the conditions newly show the field, and the field is not sent, its stored value is loaded and validated (its files' type and size against the rules validate gives them now): if it no longer fits, the save is refused with one message under the field (no longer fits this record: edit it), never the details (they describe stored data); a .required() field newly shown with nothing stored gets is required. Only a user who may write the field is held to this re-check (they can fix it): a user who may change a DEPENDS_ON field but not the field leaves its stored value as it is, even when it no longer fits. Give such inputs the field's own updatable rule, or check the stored data in mutate_before_update.

save writes only your own tables keyed by the record, never a registered resource (its policy, scope and audit would be skipped). Anything else that writes those tables (a route, a job) opens its transaction with rustcms::db::begin_write and locks the record first with ctx.lock_record::<R>(txn, key), so writes never interleave. lock_record checks no permission (a missing record is NotFound): authorize first.

Reading ​

load runs for one record at a time: its page (edit, view), the response after a save (or its idempotent replay), ctx.record(slug, key) and the data of slots beside records; never for lists, exports, relation lists and links, or the record's history (they check the record as a read does, without loading it). A load that fails, or runs out of time (the request's deadline; after a save, the time left to answer), leaves the field out and names it in the envelope's unloaded; the form then shows it as not loaded and never sends it, so it cannot be erased unseen.

Audit ​

A saved field is logged with the record's entry as its size and a keyed digest (keyed with a key of its own, derived from APP_KEY; without a keyring, a random key per process), compared before and after the save: unchanged, nothing is logged. A value that could not be loaded before the save is logged as changed (from unloaded): a save is never missing from the log. A field under .readable(..) or .audit_redact() is redacted.

The field in the panel ​

registerField(name, { edit, view? }) (SDK ui 6, Requires { ui: 6 }) registers the components. edit draws the field in create and edit forms; view draws it on view pages (without view, nothing is shown there) and in a form the user may not change (without view, edit disabled). Both get FieldProps:

Prop
value, onChange(value)the value (as load gave it, initial on create), and a new one (sent with the form)
valuesthe form's other values as they are being edited (wire format): draw differently when they change
errorsthe server's messages under the field: "" for the field, else by sub-path ("0.title")
onBusy(busy)background work (an upload): the form waits before saving
mode, record"create" or "edit", and the record's key
richNodes, collectionthe declaration's elements and collection (RichEditor field= takes them too); on view pages richNodes is empty and collection absent: draw rich text with RichTextView field=
id, label, disabled, invalid, describedBy, t, localeas for any input

Use the form widgets (RichEditor, MediaField, FormField, RepeaterRow) to look like the panel's forms. Values are frozen: build a new value, never change the one you were given. A field whose extension is not loaded says so (This field needs an extension that is not loaded); one that throws is shown as unavailable. Neither is sent.

A view page made from the form shows the field with its view. On a view page declared with an infolist, add CustomEntry::make(name, "vendor/name") with the field's widget name: its view draws it (an entry registered with registerEntry under that name draws it instead). Its value comes with the record.

Not supported ​

  • Virtual fields inside repeater rows, and resources with virtual fields as the rows of a relationship repeater (refused at boot: those rows are written without them).
  • Other inputs' conditions, computed rules and form reactions reading a virtual field (refused at boot); a reaction patching one is refused when it runs.
  • Only users who may write the field are held to required and to the re-check of a DEPENDS_ON change (above). The extension's values never hold secrets, passwords, write-only inputs or other virtual fields, in repeater rows either.
  • CSV imports never carry a virtual field and are not held to required; an imported row that changes a DEPENDS_ON field is still re-checked and refused (virtual_field_stale) when the stored value no longer fits. Actions write through their own handler (no validate: an action changing a DEPENDS_ON input keeps the field's data valid itself).

RustCMS 0.17.0 · source cfb82fa33fab · MIT OR Apache-2.0