Designing Dynamic Form & PDF Generators for Enterprise Apps
Custom fields, saved column views and conditional audit forms are one problem: users defining schema at runtime. How to model it in PostgreSQL (JSONB vs. EAV), keep it valid and versioned, and map it cleanly to PDF layouts.
The feature request that never ends
Every enterprise app eventually gets the same three requests, usually from three different customers:
- "We need to track a few extra fields on assets." Region code, warranty expiry, the name of the site manager. Every customer wants different ones.
- "Let me pick which columns show up in the table." And save that view. And export it.
- "Our inspectors fill in an audit checklist." If the answer to "Was a defect found?" is Yes, show five more questions. Then produce a signed PDF for the regulator.
They look like three separate features. They're really one: users defining schema at runtime. The developer no longer decides what the columns are. A customer admin does, through a settings screen, on a Tuesday afternoon, without a migration.
Get the underlying model right and all three features, plus PDF export, fall out of it. Get it wrong and you'll spend years writing one-off pivot queries and patching broken historical reports.
This guide walks through the architecture I'd use today on PostgreSQL: how to store user-defined fields, how to query and index them, how to model conditional forms that stay valid over time, and how to turn all of it into a clean PDF.
The core idea: separate definitions from values
Every design that works keeps two things apart:
- Definitions (metadata): what fields exist. Their key, label, type, options, validation rules and display order. Small, rarely changing, edited by admins.
- Values (data): what users actually entered. Large, constantly written, read in bulk.
Your forms, table views, validators and PDF templates are all just different renderers of the definitions, applied to the values. If you hold onto that one idea, the rest of this article is detail.
The real question is how to store the values. In PostgreSQL there are two serious candidates: EAV and JSONB.
Option 1: Entity-Attribute-Value (EAV)
EAV is the classic textbook answer. One row per value:
create table attributes (
id bigint generated always as identity primary key,
tenant_id uuid not null,
entity_type text not null, -- 'asset', 'supplier', ...
key text not null,
data_type text not null, -- 'text' | 'number' | 'date' | ...
unique (tenant_id, entity_type, key)
);
create table attribute_values (
entity_id uuid not null,
attribute_id bigint not null references attributes (id),
value_text text,
value_num numeric,
value_date date,
primary key (entity_id, attribute_id)
);
It's fully normalized, every value has a real SQL type, and adding a field is just an insert into attributes.
Now try to show a table of assets with two custom columns:
select e.id, e.name,
max(v.value_text) filter (where a.key = 'region') as region,
max(v.value_num) filter (where a.key = 'capacity_kw') as capacity_kw
from assets e
left join attribute_values v on v.entity_id = e.id
left join attributes a on a.id = v.attribute_id
group by e.id, e.name;
That's the pivot you'll be writing everywhere. Some of the costs:
- Every read is a pivot. Ten visible columns means aggregating ten rows per entity, or joining the values table ten times.
- Filtering and sorting are painful. "Region is EMEA and capacity > 50, sorted by warranty date" means three self-joins before you even get to
order by. - Constraints barely exist. You can't easily say "this field is required for this tenant", because a missing value is a missing row.
- Row explosion. 1M entities × 40 fields = 40M narrow rows, each with ~24 bytes of tuple header overhead.
EAV still earns its place in a few situations: when you need per-value history or provenance (who set this field, when, from which import), or when individual values are independently access-controlled. Most products don't need that.
Option 2: a JSONB column
The alternative is to keep custom values next to the entity:
alter table assets add column custom jsonb not null default '{}'
check (jsonb_typeof(custom) = 'object');
{ "region": "EMEA", "capacity_kw": 75, "warranty_until": "2027-03-31" }
Reading is free: the values come with the row. Filtering is a containment check. And PostgreSQL's JSONB is a real binary format with operators, indexes, and path queries, not a text blob.
What you give up is typing and validation in the schema itself. custom->'capacity_kw' could be 75, "75", or "seventy-five", unless you enforce it. Fortunately we can, and we'll do it below.
The verdict: a hybrid with three layers
| Concern | EAV | JSONB | Hybrid (recommended) |
|---|---|---|---|
| Read an entity with all its fields | Pivot / N joins | One row | One row |
| Filter on a custom field | Self-join per filter | @> with a GIN index |
GIN + promoted columns for hot fields |
| Range queries and sorting | Typed columns help | Needs expression indexes | Generated columns |
| Type safety | Per-column types | None by default | Definition table + trigger |
| Per-value history | Natural | Needs a separate log | Separate audit log |
| Schema change cost | Insert a row | Insert a row | Insert a row |
The architecture I recommend has three layers:
- A definitions table: the source of truth for what fields exist.
- A JSONB column for the values, validated against those definitions.
- Promoted columns (generated columns or expression indexes) for the handful of custom fields that get filtered and sorted heavily.
Layer 1: the field definitions
create table custom_field_definitions (
id uuid primary key default gen_random_uuid(),
tenant_id uuid not null,
entity_type text not null, -- 'asset', 'work_order', ...
key text not null check (key ~ '^[a-z][a-z0-9_]{0,62}$'),
label text not null,
type text not null check (type in
('text','long_text','number','boolean','date','select','multi_select','user')),
options jsonb not null default '[]', -- for select types: [{ "value": "emea", "label": "EMEA" }]
required boolean not null default false,
position int not null default 0,
archived_at timestamptz,
created_at timestamptz not null default now(),
unique (tenant_id, entity_type, key)
);
Three rules matter more than the exact columns:
Keys are forever. Labels are not. The admin edits the label ("Site manager" becomes "Facility lead"). The key (site_manager) never changes, and it's what's stored in the JSONB. If a label change rewrites stored data, you've coupled presentation to storage.
Never hard-delete a definition. Archive it. Old records still contain site_manager, old PDFs still reference it, and someone will ask for it back. The unique constraint also stops a new field from silently reusing an old key with a different meaning.
Never change a field's type in place. Turning capacity_kw from text into a number invalidates every existing value. Create a new field, migrate the values with a background job, then archive the old one.
Layer 2: validating JSONB against the definitions
Your application should validate first. Generate a JSON Schema from the definitions and run it with something like Ajv, which gives you good error messages for the UI. But imports, scripts and future services will bypass the app, so the database should defend itself too:
create or replace function validate_custom_fields() returns trigger
language plpgsql as $$
declare
f record;
v jsonb;
is_valid boolean;
begin
for f in
select key, type, required
from custom_field_definitions
where tenant_id = new.tenant_id
and entity_type = tg_argv[0]
and archived_at is null
loop
v := new.custom -> f.key;
if v is null or v = 'null'::jsonb then
if f.required then
raise exception 'Custom field "%" is required', f.key;
end if;
continue;
end if;
-- Assign first: PL/pgSQL would stop reading an IF condition at the CASE's own THEN.
is_valid := case f.type
when 'number' then jsonb_typeof(v) = 'number'
when 'boolean' then jsonb_typeof(v) = 'boolean'
when 'date' then jsonb_typeof(v) = 'string'
and (v #>> '{}') ~ '^\d{4}-\d{2}-\d{2}$'
when 'multi_select' then jsonb_typeof(v) = 'array'
else jsonb_typeof(v) = 'string'
end;
if not is_valid then
raise exception 'Custom field "%" must be of type %', f.key, f.type;
end if;
end loop;
return new;
end $$;
create trigger assets_validate_custom
before insert or update of custom on assets
for each row execute function validate_custom_fields('asset');
Two practical notes:
- The trigger only fires when
customchanges, so adding a new required field won't break updates to unrelated columns on old rows. You'll still want a backfill or a "needs attention" report for existing records. - To avoid lost updates when two people edit different custom fields at once, merge rather than replace:
update assets set custom = custom || $1 where id = $2. Sending back the whole object will overwrite a concurrent change.
Layer 3: querying and indexing
A single GIN index covers equality filters on any custom field:
create index assets_custom_gin on assets using gin (custom jsonb_path_ops);
-- Uses the index
select * from assets where custom @> '{"region": "emea"}';
jsonb_path_ops indexes are smaller and faster than the default operator class, but they only support containment (@>) and JSON path matches (@?, @@), not the key-exists operator ?. Write your filters as containment and you won't miss it.
GIN can't help with ranges or sorting. For the few fields that need them, promote the value into a real typed column:
alter table assets
add column capacity_kw numeric
generated always as ((custom ->> 'capacity_kw')::numeric) stored;
create index on assets (capacity_kw);
select * from assets where capacity_kw > 50 order by capacity_kw desc;
Because of the trigger above, the cast can't fail on bad data. Promotion is an optimization: the JSONB is still the source of truth, so you can add or drop generated columns without migrating any data. A lighter option is an expression index, create index on assets (((custom ->> 'capacity_kw')::numeric)), which also gives the planner statistics for that expression. Without one of these, PostgreSQL has no idea how values inside a JSONB column are distributed, and its row estimates will be guesses.
A good rule of thumb: start with JSONB + GIN for everything, and promote a field only when a real query is slow.
Feature 1: dynamic column pickers
A saved table view is just a list of column IDs, plus sorting and filters:
create table saved_views (
id uuid primary key default gen_random_uuid(),
tenant_id uuid not null,
owner_id uuid not null,
entity_type text not null,
name text not null,
columns jsonb not null, -- ["name", "status", "cf:region", "cf:capacity_kw"]
sort jsonb not null default '[]',
filters jsonb not null default '[]'
);
The dangerous part is turning that list into SQL. Never interpolate column names from user input. Resolve every ID against a registry of what's allowed, and pass custom field keys as parameters:
type Column =
| { id: string; kind: 'builtin'; sql: string } // trusted, from code
| { id: string; kind: 'custom'; key: string } // key from custom_field_definitions
const BUILTINS: Record<string, string> = {
name: 'a.name',
status: 'a.status',
updated_at: 'a.updated_at',
}
function resolveColumns(ids: string[], defs: Map<string, FieldDef>): Column[] {
return ids.flatMap((id): Column[] => {
if (id in BUILTINS) return [{ id, kind: 'builtin', sql: BUILTINS[id] }]
const key = id.startsWith('cf:') ? id.slice(3) : null
return key && defs.has(key) ? [{ id, kind: 'custom', key }] : [] // unknown → dropped
})
}
function buildQuery(cols: Column[], tenantId: string) {
const params: unknown[] = [tenantId]
const p = (v: unknown) => `$${params.push(v)}`
const select = cols.map((c, i) =>
c.kind === 'builtin'
? `${c.sql} as c${i}`
: `a.custom -> ${p(c.key)} as c${i}`,
)
return {
text: `select a.id, ${select.join(', ')} from assets a where a.tenant_id = $1`,
params,
}
}
The aliases are positional (c0, c1, …), so no user-controlled string ever becomes an identifier. The API response maps them back to column IDs, and the frontend uses the definitions for labels and formatting. Sorting and filters follow the same rule: resolve, then parameterize.
The same resolved column list later drives CSV and PDF table exports, so "what you see is what you export" comes for free.
Feature 2: conditional audit forms
Audit forms are custom fields with three extra requirements: structure (sections, repeating groups), conditional logic, and history (a submission must always render exactly as it was when it was filled in).
Templates are versioned and immutable
create table form_templates (
id uuid primary key default gen_random_uuid(),
tenant_id uuid not null,
key text not null,
name text not null,
unique (tenant_id, key)
);
create table form_template_versions (
id uuid primary key default gen_random_uuid(),
template_id uuid not null references form_templates (id),
version int not null,
schema jsonb not null,
published_at timestamptz, -- null = draft; once set, never edit
unique (template_id, version)
);
create table form_submissions (
id uuid primary key default gen_random_uuid(),
tenant_id uuid not null,
template_version_id uuid not null references form_template_versions (id),
subject_id uuid, -- the asset/site being audited
data jsonb not null default '{}',
status text not null default 'draft',
submitted_by uuid,
submitted_at timestamptz
);
Submissions point at a specific published version, never at "the template". When the safety team adds a question next month, they publish version 4; last year's audits still reference version 3 and still render correctly. That one foreign key prevents a whole class of "the old reports are broken" incidents.
Enforce immutability in the database, not just the UI: a trigger that rejects updates to schema when published_at is not null is just a few lines.
The schema document
{
"sections": [
{
"id": "inspection",
"title": "Inspection",
"fields": [
{ "key": "defect_found", "type": "boolean", "label": "Was a defect found?", "required": true },
{
"key": "severity", "type": "select", "label": "Severity", "required": true,
"options": [{ "value": "low", "label": "Low" }, { "value": "high", "label": "High" }],
"visibleIf": { "field": "defect_found", "op": "eq", "value": true }
},
{
"key": "escalated_to", "type": "user", "label": "Escalated to",
"visibleIf": { "all": [
{ "field": "defect_found", "op": "eq", "value": true },
{ "field": "severity", "op": "eq", "value": "high" }
]}
}
]
},
{
"id": "findings",
"title": "Findings",
"repeat": { "min": 0, "max": 50 },
"visibleIf": { "field": "defect_found", "op": "eq", "value": true },
"fields": [
{ "key": "location", "type": "text", "label": "Location" },
{ "key": "photo", "type": "file", "label": "Photo" }
]
}
]
}
Repeating sections are stored as arrays: "findings": [{ "location": "…", "photo": "…" }, …].
Conditions as data, never as code
It's tempting to store conditions as JavaScript strings and eval them. Don't. They become impossible to validate, unsafe to run on the server, and impossible to render in a PDF service written in another language. Use a tiny expression tree instead:
type Rule =
| { all: Rule[] }
| { any: Rule[] }
| { not: Rule }
| { field: string; op: 'eq' | 'neq' | 'in' | 'gt' | 'lt' | 'filled'; value?: unknown }
export function evaluate(rule: Rule | undefined, answers: Record<string, unknown>): boolean {
if (!rule) return true
if ('all' in rule) return rule.all.every(r => evaluate(r, answers))
if ('any' in rule) return rule.any.some(r => evaluate(r, answers))
if ('not' in rule) return !evaluate(rule.not, answers)
const v = answers[rule.field]
switch (rule.op) {
case 'eq': return v === rule.value
case 'neq': return v !== rule.value
case 'in': return Array.isArray(rule.value) && rule.value.includes(v)
case 'gt': return typeof v === 'number' && v > (rule.value as number)
case 'lt': return typeof v === 'number' && v < (rule.value as number)
case 'filled': return v !== undefined && v !== null && v !== '' &&
!(Array.isArray(v) && v.length === 0)
}
}
This one function, shared between client and server, is used in three places:
- The form renderer shows and hides fields as the user types.
- The server validator treats a hidden field as not required, and strips hidden values on submit. If an inspector answers "Yes", picks a severity, then switches back to "No", the stale severity must not end up in the record.
- The PDF renderer prints only the fields that were visible.
If these three ever disagree, you'll produce PDFs containing answers the user never saw. One evaluator, one source of truth.
Audit trail
For regulated audits, also keep an append-only form_submission_events table (who changed what, when, and the old and new values), and on final submission store a hash of data together with the template version. That lets you prove later that a PDF matches the record it came from.
Feature 3: mapping it all to PDF
The common mistake is to write a PDF generator that reads the database, loops over fields and draws text. It works for one template and becomes unmaintainable by the third. Instead, split the job into a pipeline:
definitions + values ──► render model (plain JSON) ──► layout template ──► PDF
(database) (resolved, formatted) (HTML/CSS) (renderer)
Step 1: build a render model
The render model is a fully resolved, presentation-ready document. It has no database IDs, no raw option values, and no conditions left to evaluate:
interface RenderModel {
title: string
meta: { label: string; value: string }[] // site, inspector, date, template version
sections: {
title: string
rows: { label: string; value: string; kind: 'text' | 'long_text' | 'image' }[]
repeats?: { label: string; value: string }[][]
}[]
}
Building it is where all the field-type knowledge lives:
- Select fields map stored values to labels from the same template version (
"high"→"High"). - Dates and numbers are formatted with the tenant's locale and time zone, not the server's.
- Booleans become "Yes" / "No".
- User fields resolve an ID to a display name, as it was at submission time if that matters for compliance.
- Hidden fields are dropped using the same
evaluate()function.
Because the render model is plain JSON, you can snapshot it alongside the generated PDF. Re-rendering an old document then never depends on today's data or code, and you can unit-test formatting without generating a single PDF.
Step 2: user-configurable layouts
Most customers are happy with an auto-generated layout: sections in order, two-column label/value rows. Some will want their layout: a logo, a cover page, fields arranged in a specific grid, a signature block. Store that as layout metadata that references field keys, never labels or positions in the schema:
{
"page": { "size": "A4", "margin": "18mm" },
"header": { "logo": true, "title": "{{title}}" },
"blocks": [
{ "type": "meta-grid", "columns": 3 },
{ "type": "fields", "section": "inspection", "columns": 2 },
{ "type": "table", "section": "findings", "columns": ["location", "photo"] },
{ "type": "signature", "label": "Inspector signature" }
]
}
Unknown keys are skipped with a warning, so a layout survives fields being archived. Fields that aren't placed explicitly can be appended automatically in an "Other" section, so nothing a user entered silently disappears from the PDF.
Step 3: choose a renderer
| Approach | Strengths | Watch out for |
|---|---|---|
| HTML + CSS → headless Chromium (Playwright, Puppeteer) | Same skills as the web app, rich layouts, easy previews in the browser | ~100–300 MB memory per browser; reuse a browser pool |
| Typst | Fast, excellent typography, precise pagination | A new template language for your team |
| Programmatic (PDFKit, pdfmake, react-pdf) | Lightweight, no browser | Complex layouts and page breaks get painful |
For most enterprise apps I'd start with HTML + Chromium, because the preview in the app and the exported PDF can share the same template. A few print-CSS rules do most of the work:
@page { size: A4; margin: 18mm; }
section, .row, .signature { break-inside: avoid; }
thead { display: table-header-group; } /* repeat table headers on every page */
h2 { break-after: avoid; }
Chromium doesn't support CSS @page margin boxes, so running headers, footers and "Page 3 of 7" go in Playwright's headerTemplate / footerTemplate options instead.
Step 4: generate asynchronously
Never render PDFs inside the request handler. Put a job on a queue, let a worker render it, upload the result to object storage with a content hash, and notify the user. Large exports (a 400-page audit pack) then can't take down your API, and retries become safe.
Pitfalls checklist
- Labels used as keys. Renaming a field breaks data, filters and layouts. Use stable keys.
- Deleted definitions. Old records and PDFs lose meaning. Archive instead.
- Type changes in place. Create a new field and migrate.
- Template edited after publishing. Historical submissions re-render differently. Version and freeze.
- Hidden-field leakage. Stale answers end up in PDFs. Strip hidden values on the server.
- Missing
tenant_id. Put it on every table, and on every index that starts a query, and enforce it with row-level security. - Giant JSONB documents. Values over ~2 KB are TOASTed, and every update rewrites the whole value. Keep files and long attachments out of the JSON and store references instead.
- Interpolated column names. Resolve user-supplied IDs against a registry and always use parameters.
Wrapping up
User-defined schema sounds like it needs an exotic database. It doesn't. It needs discipline about a few boundaries:
- Definitions are separate from values, and keys are permanent.
- JSONB stores the values, a trigger keeps them honest, and hot fields get promoted to real columns.
- Templates are versioned and immutable, and submissions point to the exact version they were filled against.
- Conditions are data, evaluated by one shared function in the form, the validator and the PDF.
- PDFs are rendered from a resolved render model, not straight from the database.
Build these pieces once and custom fields, column pickers, audit forms and PDF exports stop being four projects. They become four views of the same model.