Behaviors Overview
Behaviors add reactive logic to forms: computed fields, conditional visibility, field synchronization.
What Are Behaviors?β
Behaviors automatically react to form changes:
import { GroupNode } from '@reformer/core';
import { computeFrom, enableWhen } from '@reformer/core/behaviors';
const form = new GroupNode({
form: {
price: { value: 100 },
quantity: { value: 1 },
total: { value: 0 },
discount: { value: 0 },
showDiscount: { value: false },
},
behavior: (path) => {
// Auto-compute total
computeFrom([path.price, path.quantity], path.total, ({ price, quantity }) => price * quantity);
// Enable discount field conditionally
enableWhen(path.discount, (form) => form.total > 500);
},
});
Available Behaviorsβ
| Behavior | Description |
|---|---|
computeFrom | Calculate field from other fields |
transformValue | Transform value on change |
enableWhen | Conditional enable/disable |
resetWhen | Reset field on condition |
copyFrom | Copy value from another field |
syncFields | Two-way synchronization |
watchField | React to field changes |
revalidateWhen | Trigger revalidation |
How Behaviors Workβ
- Define in
behavior - ReFormer sets up reactive subscriptions
- When source fields change, behavior runs automatically
// When price or quantity changes β total updates
computeFrom(
[path.price, path.quantity], // Watch these
path.total, // Update this
({ price, quantity }) => price * quantity // With this function
);
Behavior vs Validationβ
| Aspect | Validation | Behavior |
|---|---|---|
| Purpose | Check correctness | React to changes |
| Output | Errors | Side effects |
| Examples | Required, email format | Computed total, show/hide |
Next Stepsβ
- Computed Fields β
computeFrom,transformValue - Conditional Logic β
enableWhen,resetWhen - Field Sync β
copyFrom,syncFields