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="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('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."
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