Developing a Form Constructor (Drag-and-Drop Form Builder) on a Website
A form constructor is a tool that allows non-technical users to create custom forms: surveys, applications, registrations, quizzes. Key requirements: flexible field schema, visual editor with drag-and-drop, form rendering on site and answer collection.
Architecture
System consists of three independent parts:
- Builder — React editor component (drag-and-drop)
- Renderer — React component for display and filling
- Backend — API for storing schemas, collecting answers, analytics
Form schema is JSON interpreted by renderer. This provides complete flexibility without code changes when adding new field types.
Form Schema Structure (JSON Schema)
{
"id": "uuid-v4",
"title": "Callback Request",
"description": "We'll call back within 30 minutes",
"settings": {
"submit_label": "Submit Request",
"success_message": "Thank you! We'll contact you.",
"redirect_url": null,
"notify_emails": ["[email protected]"],
"allow_multiple_submissions": false
},
"fields": [
{
"id": "field_1",
"type": "text",
"label": "Name",
"placeholder": "Enter your name",
"required": true,
"validation": { "min_length": 2, "max_length": 100 }
},
{
"id": "field_2",
"type": "phone",
"label": "Phone",
"required": true,
"validation": { "pattern": "^\\+?[\\d\\s\\-\\(\\)]{7,20}$" }
},
{
"id": "field_3",
"type": "select",
"label": "Convenient call time",
"required": false,
"options": [
{ "value": "morning", "label": "9:00 – 12:00" },
{ "value": "afternoon", "label": "12:00 – 17:00" },
{ "value": "evening", "label": "17:00 – 20:00" }
]
},
{
"id": "field_4",
"type": "conditional_group",
"condition": { "field": "field_3", "operator": "equals", "value": "evening" },
"fields": [
{
"id": "field_4_1",
"type": "checkbox",
"label": "I confirm evening calls are convenient",
"required": true
}
]
}
]
}
Supported Field Types
| Type | Description |
|---|---|
text |
Single-line text |
textarea |
Multi-line text |
email |
Email with built-in validation |
phone |
Phone with mask |
number |
Number with min/max/step |
select |
Dropdown |
multiselect |
Multi-select |
radio |
Radio buttons |
checkbox |
Single checkbox |
checkbox_group |
Checkbox group |
date |
Date |
date_range |
Date range |
file |
File upload |
rating |
Star rating (1–5) |
scale |
Scale (NPS, 0–10) |
heading |
Heading (not a field) |
paragraph |
Text block |
divider |
Divider |
conditional_group |
Group with display condition |
Builder: Editor Component
Use @dnd-kit — modern react-beautiful-dnd alternative:
import { DndContext, closestCenter, DragEndEvent } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
function FormBuilder({ schema, onChange }: BuilderProps) {
const [fields, setFields] = useState(schema.fields);
function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
if (active.id !== over?.id) {
setFields((items) => {
const oldIndex = items.findIndex((i) => i.id === active.id);
const newIndex = items.findIndex((i) => i.id === over!.id);
const reordered = arrayMove(items, oldIndex, newIndex);
onChange({ ...schema, fields: reordered });
return reordered;
});
}
}
return (
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={fields.map(f => f.id)} strategy={verticalListSortingStrategy}>
{fields.map(field => (
<SortableFieldCard
key={field.id}
field={field}
onEdit={(updated) => updateField(field.id, updated)}
onDelete={() => removeField(field.id)}
/>
))}
</SortableContext>
</DndContext>
);
}
Left toolbar — field type palette. Dragging from palette to canvas adds new field.
Renderer: Rendering and Validation
Renderer works with same JSON schema. Validation via React Hook Form with dynamic field registration:
import { useForm } from 'react-hook-form';
function FormRenderer({ schema, onSubmit }: RendererProps) {
const { register, handleSubmit, watch, formState: { errors } } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
{schema.fields.map(field => (
<FormField
key={field.id}
field={field}
register={register}
errors={errors}
watch={watch}
/>
))}
<button type="submit">{schema.settings.submit_label}</button>
</form>
);
}
function FormField({ field, register, errors, watch }) {
// Conditional logic: show field only if condition met
if (field.condition) {
const watchValue = watch(field.condition.field);
const conditionMet = evaluateCondition(watchValue, field.condition);
if (!conditionMet) return null;
}
const rules = buildValidationRules(field);
switch (field.type) {
case 'text':
case 'email':
case 'phone':
return (
<div>
<label>{field.label}{field.required && ' *'}</label>
<input {...register(field.id, rules)} placeholder={field.placeholder} />
{errors[field.id] && <span>{errors[field.id].message}</span>}
</div>
);
case 'select':
return (
<div>
<label>{field.label}</label>
<select {...register(field.id, rules)}>
<option value="">Select...</option>
{field.options.map(opt => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
</div>
);
// ... other types
}
}
Database
CREATE TABLE forms (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(255) NOT NULL,
slug VARCHAR(100) UNIQUE,
schema JSONB NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
created_by INTEGER,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE form_submissions (
id BIGSERIAL PRIMARY KEY,
form_id UUID REFERENCES forms(id),
data JSONB NOT NULL, -- { "field_1": "John", "field_2": "+79991234567" }
metadata JSONB DEFAULT '{}', -- IP, user agent, UTM
submitted_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_submissions_form ON form_submissions (form_id, submitted_at DESC);
CREATE INDEX idx_submissions_data ON form_submissions USING gin(data);
JSONB for answers is correct: each form structure is unique, fixed table schema doesn't fit. GIN index enables searching by specific field values.
Form Submission Handler
// POST /api/forms/{slug}/submit
async function submitForm(req: Request, res: Response) {
const form = await getFormBySlug(req.params.slug);
if (!form || !form.is_active) return res.status(404).json({ error: 'Form not found' });
const schema = form.schema;
const errors = validateSubmission(schema.fields, req.body);
if (Object.keys(errors).length) {
return res.status(422).json({ errors });
}
const submission = await saveSubmission(form.id, req.body, {
ip: req.ip,
user_agent: req.headers['user-agent'],
referer: req.headers.referer,
});
// Notifications
if (schema.settings.notify_emails?.length) {
await sendNotificationEmail(form, submission);
}
if (schema.settings.webhook_url) {
await triggerWebhook(schema.settings.webhook_url, submission);
}
return res.json({
success: true,
message: schema.settings.success_message,
redirect: schema.settings.redirect_url,
});
}
Answer Analytics
For each form — page with aggregated statistics:
- Answer count by day (chart)
- For
select/radio/checkbox_group— answer distribution (pie chart) - For numeric fields — average, median, range
- Export all answers to CSV/Excel
-- Answer distribution for select field
SELECT
data->>'field_3' AS answer,
COUNT(*) AS count,
ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (), 1) AS percent
FROM form_submissions
WHERE form_id = $1
AND data ? 'field_3'
GROUP BY data->>'field_3'
ORDER BY count DESC;
Implementation Timeline
Constructor with basic field types (text, email, select, checkbox), no conditional logic — 10–12 business days. Full field types, conditional logic, file fields, answer analytics, CSV export, webhooks, iframe embedding — 16–22 business days.







