Advanced Forms
Explore advanced features of the Form Builder like dynamic updates and serialization.
Beyond one-time configuration, the form builder can inspect, modify, clone, and serialize form definitions.
Dynamic Form Management
Modify a form configuration after creation:
| Method | Description |
|---|---|
.updateField(fieldId, updates) | Modifies an existing field's configuration |
.removeField(fieldId) | Removes a field |
.getField(fieldId) | Returns a field's configuration, or undefined |
.getFields() | Returns a flat array of all field configurations |
.getRows() | Returns all row configurations |
.clear() | Removes all fields and rows |
import { rilay } from '@/lib/rilay';
import { form } from '@rilaykit/forms';
const myDynamicForm = form.create(rilay, 'dynamic-form')
.add({ id: 'username', type: 'text', props: { label: 'Username' } });
if (shouldAddEmail) {
myDynamicForm.add({ id: 'email', type: 'email', props: { label: 'Email' } });
}
myDynamicForm.updateField('username', {
props: { label: 'Please enter your desired username' }
});
const formConfig = myDynamicForm.build();Builder methods mutate the builder instance. To create variations, use .clone() first.
Cloning
.clone(newFormId?) deep-copies the builder so variations don't affect the original.
const baseForm = form.create(rilay, 'base-form')
.add({ id: 'name', type: 'text', props: { label: 'Name' } });
const adminForm = baseForm.clone('admin-form')
.add({ id: 'adminNotes', type: 'textarea', props: { label: 'Admin Notes' } });
// baseForm is unaffectedSerialization (JSON Import/Export)
.toJSON() exports the form structure as a JSON-serializable object; .fromJSON(json) populates a builder from one. Use this to store definitions in a database, drive a visual form builder, or send structures over the network.
const originalForm = form.create(rilay, 'question-form')
.add({ id: 'question', type: 'text', props: { label: 'Your Question' } });
const jsonString = JSON.stringify(originalForm.toJSON());
// Later, or in another environment
const rehydratedForm = form.create(rilay).fromJSON(JSON.parse(jsonString));
const formConfig = rehydratedForm.build();fromJSON replaces the content of an existing builder — call it on a freshly created builder to avoid mutating a shared instance.
Introspection
.getStats() returns a structural overview, useful for debugging:
const stats = myFormBuilder.getStats();
/*
{
totalFields: 5,
totalRows: 4,
averageFieldsPerRow: 1.25,
maxFieldsInRow: 2,
minFieldsInRow: 1,
totalRepeatables: 0,
totalRepeatableFields: 0
}
*/