Advanced Forms
WildflowerJS supports complex form patterns including dynamic fields, form arrays, intrinsic handling with data-model-trim and data-model-number, and input modifiers.
Form Arrays and Dynamic Fields
Handle variable-length form data with complex nested arrays and dynamic field management:
<div data-component="form-arrays">
<form data-action="handleSubmit">
<div class="d-flex justify-content-between align-items-center mb-3">
<h6 class="mb-0">Contacts <span class="badge bg-primary" data-bind="contacts.length"></span></h6>
<button type="button" data-action="addContact" class="btn btn-primary btn-sm">Add Contact</button>
</div>
<div data-list="contacts">
<template>
<div class="mb-3 p-3 border rounded">
<div class="d-flex gap-2 mb-2">
<input type="text" data-model="name" class="form-control" placeholder="Name">
<input type="email" data-model="email" class="form-control" placeholder="Email">
<button type="button" data-action="removeContact" class="btn btn-danger btn-sm">×</button>
</div>
</div>
</template>
</div>
<div data-show="contacts.length === 0" class="text-muted text-center p-3">
No contacts yet. Click "Add Contact" to start.
</div>
<div data-show="contacts.length > 0" class="mt-3">
<button type="submit" class="btn btn-primary me-2">Submit</button>
<button type="button" data-action="resetForm" class="btn btn-secondary">Reset</button>
</div>
</form>
<div class="mt-3" data-show="result">
<div class="alert alert-success">
Submitted: <code data-bind="result"></code>
</div>
</div>
</div>
<option value="">Select type...</option>
<option value="web">Web Application</option>
<option value="mobile">Mobile App</option>
<option value="desktop">Desktop Software</option>
<option value="api">API/Backend</option>
<option value="game">Game Development</option>
</select>
</div>
</div>
<div class="mb-3">
<label class="form-label">Project Description:</label>
<textarea data-model="form.description" class="form-control" rows="3" placeholder="Describe your project goals and requirements..."></textarea>
</div>
</div>
<div class="mb-4">
<div class="d-flex justify-content-between align-items-center mb-3">
<h5>👥 Team Members <span class="badge bg-primary"><span data-bind="form.teamMembers.length"></span></span></h5>
<div>
<button type="button" data-action="addMember" class="btn btn-primary btn-sm me-2">
➕ Add Member
</button>
<button type="button" data-action="addSampleTeam" class="btn btn-info btn-sm">
🎯 Sample Team
</button>
</div>
</div>
<div data-list="form.teamMembers">
<template>
<div class="card mb-3 team-member-card">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<h6 class="mb-0">
<span class="badge bg-secondary me-2">#<span data-bind="number"></span></span>
<span data-bind="name || 'New Team Member'"></span>
</h6>
<div>
<button type="button" data-action="duplicateMember" class="btn btn-secondary btn-sm me-1" title="Duplicate this member">
📋
</button>
<button type="button" data-action="removeMember" class="btn btn-danger btn-sm" title="Remove this member">
🗑️
</button>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label">Full Name: *</label>
<input type="text" data-model="name" class="form-control" placeholder="Enter full name">
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Email Address: *</label>
<input type="email" data-model="email" class="form-control" placeholder="name@example.com">
</div>
</div>
<div class="row">
<div class="col-md-4 mb-3">
<label class="form-label">Primary Role: *</label>
<select data-model="role" class="form-select">
<option value="">Select role...</option>
<option value="frontend">Frontend Developer</option>
<option value="backend">Backend Developer</option>
<option value="fullstack">Full Stack Developer</option>
<option value="designer">UI/UX Designer</option>
<option value="manager">Project Manager</option>
<option value="qa">QA Engineer</option>
<option value="devops">DevOps Engineer</option>
<option value="analyst">Business Analyst</option>
</select>
</div>
<div class="col-md-4 mb-3">
<label class="form-label">Experience Level:</label>
<select data-model="level" class="form-select">
<option value="">Select level...</option>
<option value="junior">Junior (0-2 years)</option>
<option value="mid">Mid-level (3-5 years)</option>
<option value="senior">Senior (6-10 years)</option>
<option value="lead">Lead (10+ years)</option>
</select>
</div>
<div class="col-md-4 mb-3">
<label class="form-label">Hourly Rate ($):</label>
<input type="number" data-model="hourlyRate" class="form-control" min="0" max="500" step="5" placeholder="50">
</div>
</div>
<div class="mb-3">
<label class="form-label">Skills & Technologies:</label>
<div class="input-group mb-2">
<input type="text"
data-model="newSkill"
class="form-control"
placeholder="Add a skill or technology..."
data-action="keydown:handleSkillKeydown">
<button type="button" data-action="addSkill" class="btn btn-primary">
Add Skill
</button>
</div>
<div class="skills-container" data-show="skills.length > 0">
<div data-list="skills">
<template>
<span class="badge bg-info me-1 mb-1 skill-badge">
<span data-bind="$item"></span>
<button type="button"
data-action="removeSkill"
class="btn-close btn-close-white ms-1"
style="font-size: 0.6em;"
title="Remove skill"></button>
</span>
</template>
</div>
</div>
<div data-show="skills.length === 0" class="text-muted small">
No skills added yet. Type a skill above and click "Add Skill".
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label">Availability:</label>
<select data-model="availability" class="form-select">
<option value="">Select availability...</option>
<option value="full-time">Full-time (40h/week)</option>
<option value="part-time">Part-time (20h/week)</option>
<option value="contract">Contract/Project-based</option>
<option value="consulting">Consulting (As needed)</option>
</select>
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Start Date:</label>
<input type="date" data-model="startDate" class="form-control">
</div>
</div>
</div>
</div>
</template>
</div>
<div data-show="form.teamMembers.length === 0" class="alert alert-info text-center">
<h6>👥 No team members added yet</h6>
<p class="mb-2">Every great project starts with a great team. Click "Add Member" to get started!</p>
<button type="button" data-action="addMember" class="btn btn-primary">
Add First Team Member
</button>
</div>
</div>
<!-- Team Summary -->
<div class="mb-4" data-show="form.teamMembers.length > 0">
<h6>Team Summary</h6>
<div class="row text-center">
<div class="col-md-3 mb-2">
<div class="card">
<div class="card-body p-2">
<div class="h5 mb-1" data-bind="form.teamMembers.length"></div>
<small class="text-muted">Team Members</small>
</div>
</div>
</div>
<div class="col-md-3 mb-2">
<div class="card">
<div class="card-body p-2">
<div class="h5 mb-1" data-bind="totalSkills"></div>
<small class="text-muted">Total Skills</small>
</div>
</div>
</div>
<div class="col-md-3 mb-2">
<div class="card">
<div class="card-body p-2">
<div class="h5 mb-1">$<span data-bind="estimatedCost"></span></div>
<small class="text-muted">Est. Weekly Cost</small>
</div>
</div>
</div>
<div class="col-md-3 mb-2">
<div class="card">
<div class="card-body p-2">
<div class="h5 mb-1" data-bind="completionRate"></div>%
<small class="text-muted">Profile Complete</small>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions">
<button type="submit"
class="btn btn-primary me-2"
data-bind-attr="{ disabled: form.teamMembers.length === 0 }">
🚀 Submit Project
</button>
<button type="button" data-action="resetForm" class="btn btn-secondary me-2">
🔄 Reset Form
</button>
<button type="button" data-action="exportTeam" class="btn btn-info">
📊 Export Team Data
</button>
</div>
</form>
<div class="mt-4" data-show="submissionResult">
<div class="alert alert-success">
<h6>✅ Project Team Submitted Successfully!</h6>
<p>Your project "<strong><span data-bind="form.projectName"></span></strong>" has been submitted with <strong><span data-bind="form.teamMembers.length"></span></strong> team member(s).</p>
<details>
<summary>View submitted data</summary>
<pre class="mt-2"><code data-bind="submissionResult"></code></pre>
</details>
</div>
</div>
<div class="mt-3" data-show="exportData">
<div class="alert alert-info">
<h6>📊 Team Export Data</h6>
<p>Copy this data to use in other systems:</p>
<textarea id="export-textarea" class="form-control" rows="10" readonly data-bind="exportData"></textarea>
<button type="button" data-action="copyExportData" class="btn btn-primary btn-sm mt-2">
Copy to Clipboard
</button>
</div>
</div>
</div>
<style>
.team-member-card {
transition: all 0.3s ease;
border-left: 4px solid #007bff;
}
.team-member-card:hover {
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
transform: translateY(-2px);
}
.skills-container {
max-height: 100px;
overflow-y: auto;
padding: 0.5rem;
background: #f8f9fa;
border-radius: 0.25rem;
}
.skill-badge {
transition: all 0.2s ease;
}
.skill-badge:hover {
transform: scale(1.05);
}
.form-actions {
background: #f8f9fa;
padding: 1rem;
border-radius: 0.375rem;
border: 1px solid #dee2e6;
}
</style>
wildflower.component('form-arrays', {
state: {
contacts: [],
result: '',
nextId: 1
},
addContact() {
this.contacts.push({ id: this.nextId++, name: '', email: '' })
},
removeContact(e, el, detail) {
this.contacts.splice(detail.index, 1)
},
handleSubmit(event) {
event.preventDefault()
this.result = JSON.stringify(this.contacts.map(c => ({ name: c.name, email: c.email })))
},
resetForm() {
this.contacts = []
this.result = ''
}
})
Intrinsic Form Handling
WildflowerJS provides built-in form handling with automatic synchronization, debouncing, and advanced performance optimizations:
- Form data is synchronized to state before action methods are called
- Built-in debouncing prevents excessive updates during typing
- Automatic form validation when
data-validateis present - No need for explicit event.preventDefault() calls
- Advanced event modifiers for fine-grained control
- Automatic cleanup and memory management
Input Modifiers
Add attributes to data-model inputs to control how values are processed:
<div data-component="modifier-demo">
<div class="mb-3">
<label class="form-label">Without modifiers:</label>
<input type="text" data-model="raw" class="form-control"
placeholder="Try ' hello ' with spaces">
<div class="mt-1 p-2 border rounded bg-light">
Stored: "<strong data-bind="raw"></strong>"
— length: <strong data-bind="rawLen"></strong>
</div>
</div>
<div class="mb-3">
<label class="form-label">With data-model-trim:</label>
<input type="text" data-model="trimmed" data-model-trim
class="form-control" placeholder="Try ' hello ' with spaces">
<div class="mt-1 p-2 border rounded bg-light">
Stored: "<strong data-bind="trimmed"></strong>"
— length: <strong data-bind="trimLen"></strong>
</div>
</div>
<div class="mb-3">
<label class="form-label">With data-model-number:</label>
<input type="number" data-model="price" data-model-number
class="form-control" placeholder="Enter a number">
<div class="mt-1 p-2 border rounded bg-light">
typeof: <strong data-bind="priceType"></strong>
— doubled: <strong data-bind="doubled"></strong>
</div>
</div>
</div>
wildflower.component('modifier-demo', {
state: { raw: '', trimmed: '', price: 0 },
computed: {
rawLen() { return this.raw.length },
trimLen() { return this.trimmed.length },
priceType() { return typeof this.price },
doubled() { return this.price * 2 }
}
})
To reduce expensive work during fast typing, debounce the action handler rather than the state update:
<!-- State updates immediately; onSearch runs 300ms after the last keystroke -->
<input data-model="search" data-action="input:onSearch" data-event-debounce="300">
<!-- Model modifiers still apply to state sync -->
<input data-model="query" data-model-trim data-action="input:onSearch" data-event-debounce="500">
Automatic Form Submission
When a form has data-action, WildflowerJS automatically prevents the default submit and syncs all data-model fields to state before calling your method:
<form data-action="handleSubmit">
<input data-model="email" type="email">
<input data-model="message" data-model-trim>
<button type="submit">Send</button>
</form>
handleSubmit() {
// No event.preventDefault() needed
// this.email and this.message are already synced
console.log('Sending:', this.email, this.message)
}
Advanced Event Modifiers
WildflowerJS provides additional event modifiers for complex interactions:
<div data-component="form-modal-demo">
<h3>Advanced Event Modifiers</h3>
<!-- Self-only events: Only trigger when clicking the element itself -->
<div data-action="handleContainerClick" data-event-self
style="padding: 20px; border: 2px solid #007bff; background: #f8f9fa;">
<h5>Self-Only Container (data-event-self)</h5>
<p>Click this container background (not the text) to trigger the action.</p>
<button data-action="handleButtonClick">Button inside container</button>
<p>Clicking the button above won't trigger the container's action.</p>
</div>
<div class="mt-3">
<button data-action="openModal">Open Modal (with outside click)</button>
</div>
<!-- Modal that closes when clicking outside -->
<div data-show="modalOpen"
data-action="closeModal"
data-event-outside
style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; display: flex; align-items: center; justify-content: center;">
<div style="background: white; padding: 30px; border-radius: 8px; max-width: 400px; margin: 20px;">
<p>Click anywhere outside this modal to close it, or use the button below.</p>
<button data-action="closeModal" class="btn btn-secondary">Close Modal</button>
</div>
</div>
<div class="mt-3">
<p><strong>Last Action:</strong> <span data-bind="lastAction"></span></p>
</div>
</div>
Component Definition
wildflower.component('form-modal-demo', {
state: {
modalOpen: false,
lastAction: 'None'
},
handleContainerClick() {
this.lastAction = 'Container clicked (self-only)'
},
handleButtonClick() {
this.lastAction = 'Button inside container clicked'
},
openModal() {
this.modalOpen = true
this.lastAction = 'Modal opened'
},
closeModal() {
this.modalOpen = false
this.lastAction = 'Modal closed (outside click or button)'
}
})
Event Modifier Reference
| Modifier | Purpose | Example Use Case |
|---|---|---|
data-event-self |
Only trigger when event target is the element itself | Prevent child element clicks from bubbling |
data-event-outside |
Trigger when clicking outside the element | Close modals, dropdowns, and menus |
data-event-stop |
Call event.stopPropagation() | Prevent event bubbling to parent elements |
data-event-prevent |
Call event.preventDefault() | Prevent default browser behavior |
data-event-once |
Event listener triggers only once | One-time initialization actions |
data-event-passive |
Use passive event listener | Better performance for scroll/touch events |
data-event-capture |
Use capture phase event listener | Handle events during capture phase |
Early Submit Edge Case
This is narrow but worth knowing if you build forms that depend on event.preventDefault() to stop a submit.
Action handlers fire on click immediately, even if the component's init() hook hasn't completed yet. The framework queues those calls and replays them after init. For typical handlers this is invisible. For form submits it has one wrinkle: the captured event object is the original DOM event, and by the time the queued call replays, the browser has already processed the event's default action. Calling event.preventDefault() at that point is a no-op.
In practice this affects:
- A user submitting a form during the brief window between mount and
init()completing. - Components that subscribe to slow stores (
init()waits for store readiness, widening the window). - Tests that synchronously dispatch a submit immediately after
_scanForComponents().
Workaround if your form handler must reliably prevent submission: defer the prevent into init() using a one-shot guard, or use data-event-prevent on the form element itself (the framework intercepts the submit before user-code timing matters):
<!-- ✅ Right: framework prevents the default before any handler runs -->
<form data-action="submit" data-event-prevent>
...
</form>
Most apps will never hit this; the window between mount and init is sub-frame for components without store subscriptions, and natural form submits during that window are rare. But it's worth knowing the mechanism if you ever see "form submitted even though I called preventDefault."
Cross-Field Rules in Depth
The basic form of a rule is a name and an expression. The object form adds three controls:
rules: {
'destination': {
check: 'pickup != "" || address != ""',
when: 'delivery', // an ordinary boolean state property, checked for truthiness
message: 'Provide a pickup point or an address',
fields: ['pickup', 'address'] // which inputs get the invalid class
}
}
| Key | Type | Required | Default |
|---|---|---|---|
check | string or function | Yes | n/a |
message | string | No | the rule's name |
when | string or function | No | always in force |
fields | array of strings | No | see below |
check and when accept the same two forms: a CSP-safe expression string evaluated over state and computed names, or a function bound to the component. Only check is required; a rule with no when: is always in force.
when: gating
when: resolves the same way check: does: delivery in the example above is a plain state property on the component, most likely a checkbox bound with data-model="delivery". A rule with when: is checked only while its condition holds, so a delivery-address rule that applies only when that checkbox is checked needs no conditional logic in the check itself; gate it and the check stays a clean statement of the requirement.
A full expression works here too, with the same operators available everywhere else in the framework: when: 'delivery && accepted' gates the rule on only once both are true.
when: may also be a function, for a gate that a string expression can't express, such as checking membership in a list:
rules: {
'destination': {
check: 'pickup != "" || address != ""',
when() { return ['standard', 'express', 'freight'].includes(this.method); },
fields: ['pickup', 'address']
}
}
It runs bound to the component and follows the same return-value contract as a function check:: the value returned IS the verdict, and a promise, undefined, or a string is diagnosed (WF-234) and the rule is skipped for that pass rather than guessed at.
<div data-component="shipping-when-demo">
<form data-validate-on="submit,blur" data-action="save">
<div class="mb-3">
<label class="form-label">Shipping method</label>
<select data-model="method" class="form-select">
<option value="standard">Standard</option>
<option value="express">Express courier</option>
<option value="pickup">Pickup in store</option>
<option value="freight">Freight</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Pickup point</label>
<input type="text" data-model="pickup" data-model-trim class="form-control" placeholder="e.g. Main St depot">
</div>
<div class="mb-3">
<label class="form-label">Or an address</label>
<input type="text" data-model="address" data-model-trim class="form-control" placeholder="e.g. 42 Meadow Lane">
<div class="error-message" data-error-for="destination"></div>
</div>
<div class="form-check mb-2">
<input type="checkbox" data-model="rush" class="form-check-input" id="when-demo-rush">
<label class="form-check-label" for="when-demo-rush">Rush order</label>
</div>
<div class="form-check mb-2" data-show="rush">
<input type="checkbox" data-model="acknowledgeSurcharge" class="form-check-input" id="when-demo-ack">
<label class="form-check-label" for="when-demo-ack">I accept the rush surcharge</label>
</div>
<div class="error-message" data-error-for="surcharge"></div>
<button type="submit" class="btn btn-primary mt-2">Place order</button>
<button type="button" class="btn btn-danger mt-2" data-show="placed" data-action="resetForm">Reset</button>
</form>
<div class="alert alert-success mt-3" data-show="placed">Order placed.</div>
</div>
wildflower.component('shipping-when-demo', {
state: {
method: 'standard', pickup: '', address: '',
rush: false, acknowledgeSurcharge: false, placed: false
},
rules: {
// when: is a function here because a CSP-safe string can't
// express an array-membership check. The check: can stay a plain
// string because the inputs use data-model-trim, so a space
// alone never reaches state as a "value".
'destination': {
check: 'pickup != "" || address != ""',
when() { return ['standard', 'express', 'freight'].includes(this.method); },
fields: ['pickup', 'address'],
message: 'Provide a pickup point or an address; only pickup in store needs neither'
},
// when: is a plain string here, since a single checkbox is all
// the gate needs.
'surcharge': {
check: 'acknowledgeSurcharge == true',
when: 'rush',
fields: ['acknowledgeSurcharge'],
message: 'Accept the rush surcharge to place a rush order'
}
},
save() {
this.placed = true;
},
// Explicit reset for anyone who won't reach for the demo's own Reset
// button in the preview header.
resetForm() {
this.method = 'standard';
this.pickup = '';
this.address = '';
this.rush = false;
this.acknowledgeSurcharge = false;
this.placed = false;
},
// Changing anything after a successful submit clears the confirmation,
// so you can try a different combination and see the rules run again.
watch: {
// A new method needs its own destination entered fresh, so a
// leftover pickup point from a prior method doesn't silently
// satisfy this one.
method() { this.placed = false; this.pickup = ''; this.address = ''; },
pickup() { this.placed = false; },
address() { this.placed = false; },
// Turning rush off also clears its dependent checkbox, so it
// doesn't come back pre-checked the next time rush is turned on.
rush() { this.placed = false; if (!this.rush) this.acknowledgeSurcharge = false; },
acknowledgeSurcharge() { this.placed = false; }
}
});
.error-message { color: #dc3545; font-size: 0.85rem; min-height: 1.2em; margin-top: 0.25rem; }
.form-control.invalid, .form-select.invalid { border-color: #dc3545; background: #fff5f5; }
fields: attribution
Without fields:, a string rule adds the invalid class to every data-model input whose state variable the check reads. Declare fields: when the check reads more than it should flag. An either-or rule reads both fields but you may want only one highlighted, or both; that choice is yours, per rule.
A function check has no expression for the framework to read, so this inference doesn't apply to it: without fields:, a failing function check still blocks submit and still writes its message to a data-error-for matching the rule's name, but no input gets the invalid class. Declare fields: on any function check that should highlight specific inputs.
<div data-component="fields-demo">
<form data-validate-on="submit,blur" data-action="save">
<div class="row">
<div class="col-6 mb-3">
<label class="form-label">Quantity</label>
<input type="number" data-model="qty" data-model-number class="form-control">
<div class="error-message" data-error-for="qty"></div>
</div>
<div class="col-6 mb-3">
<label class="form-label">Price each</label>
<input type="number" data-model="price" data-model-number class="form-control">
</div>
</div>
<p class="text-muted mb-1">Budget: $500</p>
<div class="error-message" data-error-for="budget"></div>
<button type="submit" class="btn btn-primary mt-2">Place order</button>
<button type="button" class="btn btn-danger mt-2" data-show="placed" data-action="resetForm">Reset</button>
</form>
<div class="alert alert-success mt-3" data-show="placed">Order placed.</div>
</div>
wildflower.component('fields-demo', {
state: { qty: 0, price: 0, placed: false },
rules: {
// String check, no fields: given, so it auto-marks "qty", the
// only data-model input the expression reads.
'Quantity must be positive': 'qty > 0',
// Function check, no fields: given, so nothing gets the invalid
// class, even though this still blocks.
'budget': {
check() { return (this.qty * this.price) <= 500; },
message: 'Total exceeds the $500 budget'
}
},
save() {
this.placed = true;
},
// Explicit reset for anyone who won't reach for the demo's own Reset
// button in the preview header.
resetForm() {
this.qty = 0;
this.price = 0;
this.placed = false;
},
// Changing anything after a successful submit clears the confirmation,
// so you can try a different combination and see the rules run again.
watch: {
qty() { this.placed = false; },
price() { this.placed = false; }
}
});
.error-message { color: #dc3545; font-size: 0.85rem; min-height: 1.2em; margin-top: 0.25rem; }
.form-control.invalid, .form-select.invalid { border-color: #dc3545; background: #fff5f5; }
Function checks
A check may be a function instead of an expression string. It runs bound to the component context, so state, computed properties, and methods are all reachable:
rules: {
'Quantity fits remaining stock': {
check() { return Number(this.qty) <= this.remainingStock; },
fields: ['qty']
}
}
A function check that throws does not silently pass or fail the form. The rule is skipped for that pass, the other rules and per-input validation still run, and the dev build reports the rule by name with the error, once (WF-229).
Computed properties in rules
String checks may reference computed names alongside state. A rule like 'total <= creditLimit' where total is computed works as written; the rule reads the computed's current value on each validation pass.
What rules are not
Rules run at the form boundary, where the user can repair the problem before anything submits. Checks a user cannot act on, like internal consistency assumptions, do not belong here, since blocking a submit on one leaves no way forward. Keep the validation surface to conditions a person can fix.
Form Best Practices
✅ Do
- Use data-model for two-way binding
- Use simple data-action="methodName" on forms
- Leverage built-in debouncing with data-event-debounce on action handlers
- Add data-validate for automatic validation
- Use appropriate input types with validation attributes
- Trust framework's intrinsic form handling
❌ Don't
- Use overcomplicated data-action="submit:method" syntax
- Manually call event.preventDefault() in form actions
- Validate on every keystroke without debouncing
- Show errors before user finishes typing
- Forget to sanitize form data before submission
- Use generic error messages