Forms
Send a form's fields to an SDK method with Salla.form, from a React submit or change handler.
Read this when a form should call an SDK method with its fields, such as an add-to-cart form or a comment box.
Salla.form reads every field of a form and passes them to an SDK method by name.
The field names become the method's payload, so <input name="quantity"> arrives as quantity.
Submit a form
Call Salla.form.submit from your submit handler with the method name and the native event:
export function CommentForm({ productId }: { productId: number }) {
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = e.currentTarget; // React empties e.currentTarget once the handler awaits
try {
await window.salla?.form.submit('comment.add', e.nativeEvent);
form.reset();
} catch {
// the SDK already showed the error message
}
}
return (
<form onSubmit={onSubmit}>
<input type="hidden" name="type" value="product" />
<input type="hidden" name="id" value={productId} />
<textarea name="comment" required maxLength={500} />
<button type="submit">Send</button>
</form>
);
}This calls Salla.comment.add({ type: 'product', id, comment }) and returns its promise.
The method name is the module and the method, as in 'cart.addItem' or 'order.sendInvoice'.
A full URL (starting with https://) sends the fields to that address instead, as a POST.
Without waiting
Salla.form.onSubmit(name, event) does the same but returns false instead of the promise. The engine's add-to-cart form uses it:
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
window.salla?.form.onSubmit('cart.addItem', e.nativeEvent);
};Pass the native event (e.nativeEvent). The SDK reads the form and the button that submitted it from the browser's event.
Run on change
Salla.form.onChange(name, event) calls the method each time a field changes, but only when every required field is filled.
The cart page uses it to update an item as soon as the quantity changes:
<form onChange={(e) => window.salla?.form.onChange('cart.updateItem', e)}>
<input type="hidden" name="id" value={item.id} />
<input type="number" name="quantity" defaultValue={item.quantity} />
</form>Here the React event works, because the SDK reads event.currentTarget. It returns true when it called the method.
What the method receives
| Your form | The method gets |
|---|---|
A <form> | Its fields as FormData |
An element with data-json='{"id":1}' | That JSON, parsed |
Most methods accept FormData or a plain object with the same field names, so the same method works from a form and from code.
Gotchas
- A submit button inside a
<salla-button>shows a loading spinner until the call finishes. That needs the native event: the React event does not carry the button. onChangewith an incomplete form does nothing and returnsfalse. Mark the fields that must be filled withrequired.- To call a method with values that are not in the form, call it directly:
Salla.cart.addItem({ id, quantity }).