Enviar un formulario
Carga los campos de un formulario, los renderiza y envía los datos introducidos por el usuario con FormData.postFormsData().
Qué hace este ejemplo:
- Obtiene la configuración del formulario desde la plataforma OneEntry
- Recoge los datos que introduce el usuario en un formulario de contacto.
- Convierte cada valor al formato que espera el tipo de su campo (consulta prepareValue()).
- Envía los datos recogidos a la API de OneEntry.
Requisitos previos:
- Un PROJECT_URL y un APP_TOKEN válidos para la API de OneEntry.
- Un formulario en OneEntry identificado por un marcador (p. ej., 'contact_us').
- Campos configurados en ese formulario (este ejemplo maneja campos string, text, list, radioButton y button).
Notas:
- Maneja los errores de la API y muestra mensajes a los usuarios.
- Mantén los campos del formulario y sus marcadores sincronizados con la configuración del backend.
- Por defecto (
isShell: true), el SDK devuelve un objeto de error en lugar de lanzar una excepción, así que comprueba el resultado, p. ej.,'statusCode' in result. ConisShell: falselanza la excepción y los errores se manejan con try/catch. Consulta Errors.
Documentación de la plataforma:
Referencia del SDK:
Pruébalo en vivo
Ejecuta este ejemplo en el sandbox del SDK de JS. Conecta tu Project URL y App Token en la primera visita y luego abre:
Escenario
1. Importar defineOneEntry y definir PROJECT_URL y APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
2. Crear un cliente de API con defineOneEntry()
const { Forms, FormData } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. Obtener el formulario con Forms.getFormByMarker()
useEffect(() => {
Forms.getFormByMarker('contact_us').then((data: any) => {
if ('statusCode' in data) {
setErrorMsg(data.message);
setStatus('error');
return;
}
setForm(data);
const initial: Record<string, string> = {};
data?.attributes?.forEach((a: any) => { initial[a.marker] = ''; });
setValues(initial);
console.log('Form: ', data);
}).catch((err) => {
setErrorMsg(String(err));
setStatus('error');
});
}, []);
Resultado:
{
"id": 3,
"attributeSetId": 2,
"type": "data",
"localizeInfos": {
"title": "Contact us",
"titleForSite": "",
"successMessage": "Message about successful data processing",
"unsuccessMessage": "Message about unsuccessful data processing",
"urlAddress": "",
"database": "0",
"script": "0"
},
"version": 5,
"position": 1,
"identifier": "contact_us",
"processingType": "script",
"templateId": null,
"attributes": [
{
"type": "string",
"marker": "first_name",
"position": 1,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {
"requiredValidator": {
"strict": true
}
},
"initialValue": null,
"localizeInfos": {
"title": "First name"
},
"additionalFields": {}
},
{
"type": "string",
"marker": "email",
"position": 2,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {
"requiredValidator": {
"strict": true
},
"emailInspectionValidator": true
},
"initialValue": null,
"localizeInfos": {
"title": "Email"
},
"additionalFields": {}
},
{
"type": "string",
"marker": "surname",
"position": 3,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {
"stringInspectionValidator": {
"stringMax": 0,
"stringMin": 0,
"stringLength": 0
}
},
"initialValue": null,
"localizeInfos": {
"title": "Surname"
},
"additionalFields": {}
},
{
"type": "list",
"marker": "topic",
"position": 4,
"settings": {},
"isVisible": true,
"listTitles": [
{
"title": "Article",
"value": "article",
"extended": {
"type": null,
"value": null
},
"position": 1
},
{
"title": "Article-2",
"value": "article-2",
"extended": {
"type": null,
"value": null
},
"position": 2
}
],
"validators": {
"requiredValidator": {
"strict": true
}
},
"initialValue": null,
"localizeInfos": {
"title": "Topic"
},
"additionalFields": {}
},
{
"type": "text",
"marker": "text",
"position": 5,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {},
"initialValue": null,
"localizeInfos": {
"title": "Text"
},
"additionalFields": {}
},
{
"type": "button",
"marker": "send",
"position": 7,
"settings": {},
"isVisible": true,
"listTitles": [],
"validators": {},
"initialValue": null,
"localizeInfos": {
"title": "Send"
},
"additionalFields": {}
}
],
"total": "1",
"moduleFormConfigs": [
{
"id": 2,
"moduleIdentifier": "content",
"isGlobal": false,
"isClosed": false,
"viewOnlyUserData": false,
"commentOnlyUserData": false,
"entityIdentifiers": [
{
"id": "services",
"isNested": false
}
],
"ratingCalculation": "average",
"allowHalfRatings": null,
"maxRatingScale": null,
"isAnonymous": null,
"allowRerating": null,
"isRating": null
}
]
}
4. Leer la configuración de módulos del formulario
postFormsData() necesita el id de la configuración (formModuleConfigId) y el identificador de la entidad a la que está vinculado el formulario (moduleEntityIdentifier). Ambos vienen de form.moduleFormConfigs.
const moduleConfig = form.moduleFormConfigs?.[0];
const sortedFields = [...(form.attributes || [])].sort(
(a: any, b: any) => a.position - b.position,
);
5. Obtener los datos de los campos del formulario del frontend
const formData = sortedFields
.filter((f: any) => values[f.marker] !== '')
.map((f: any) => ({
marker: f.marker,
type: f.type,
value: prepareValue(f.type, values[f.marker] ?? ''),
}));
Resultado:
[
{
"marker": "first_name",
"type": "string",
"value": "John"
},
{
"marker": "email",
"type": "string",
"value": "john@example.com"
},
{
"marker": "surname",
"type": "string",
"value": "Smith"
},
{
"marker": "topic",
"type": "list",
"value": [
"article"
]
},
{
"marker": "text",
"type": "text",
"value": [
{
"plainValue": "Hello, I have a question about my order."
}
]
}
]
6. Enviar los datos del formulario con FormData.postFormsData()
const result = await FormData.postFormsData({
formIdentifier: 'contact_us',
formData,
formModuleConfigId: moduleConfig?.id || 0,
moduleEntityIdentifier: moduleConfig?.entityIdentifiers?.[0]?.id || '',
replayTo: null,
status: 'sent',
});
Resultado:
{
"formData": {
"formIdentifier": "contact_us",
"time": "2026-06-06T10:10:05.844Z",
"formData": [
{
"marker": "first_name",
"type": "string",
"value": "John"
},
{
"marker": "email",
"type": "string",
"value": "john@example.com"
},
{
"marker": "surname",
"type": "string",
"value": "Smith"
},
{
"marker": "topic",
"type": "list",
"value": [
"article"
]
},
{
"marker": "text",
"type": "text",
"value": [
{
"plainValue": "Hello, I have a question about my order."
}
]
}
],
"entityIdentifier": "services",
"fingerprint": "UQ_zhfcsr_mpdtr691jq7d",
"isUserAdmin": false,
"formModuleId": 2,
"userIdentifier": null,
"parentId": null,
"id": 172
},
"actionMessage": "Message about successful data processing"
}
Ejemplo final
import { useState, useEffect } from 'react';
// 1. Import defineOneEntry and define PROJECT_URL and APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
// 2. Create an API client with defineOneEntry()
const { Forms, FormData } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
// Prepare value for API submission by field type
function prepareValue(type: string, value: string) {
if (type === 'text') return [{ plainValue: value }];
if (type === 'list' || type === 'radioButton') return [value];
return value;
}
const typeMap: Record<string, string> = {
integer: 'number',
real: 'number',
float: 'number',
date: 'date',
time: 'time',
dateTime: 'datetime-local',
};
const ContactForm = () => {
const [form, setForm] = useState<any>(null);
const [values, setValues] = useState<Record<string, string>>({});
const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
const [errorMsg, setErrorMsg] = useState('');
// 3. Get form with Forms.getFormByMarker()
useEffect(() => {
Forms.getFormByMarker('contact_us').then((data: any) => {
if ('statusCode' in data) {
setErrorMsg(data.message);
setStatus('error');
return;
}
setForm(data);
const initial: Record<string, string> = {};
data?.attributes?.forEach((a: any) => { initial[a.marker] = ''; });
setValues(initial);
console.log('Form: ', data);
}).catch((err) => {
setErrorMsg(String(err));
setStatus('error');
});
}, []);
if (status === 'error' && !form) return <p role="alert">{errorMsg}</p>;
if (!form) return <div>Loading...</div>;
const sortedFields = [...(form.attributes || [])].sort(
(a: any, b: any) => a.position - b.position,
);
const handleSubmit = async (e: any) => {
e.preventDefault();
if (!form) return;
setStatus('loading');
// 4. Read the form's module config
const moduleConfig = form.moduleFormConfigs?.[0];
// 5. Get field data from the frontend form
const formData = sortedFields
.filter((f: any) => values[f.marker] !== '')
.map((f: any) => ({
marker: f.marker,
type: f.type,
value: prepareValue(f.type, values[f.marker] ?? ''),
}));
console.log('Form Data ', formData);
// 6. Post form data with FormData.postFormsData()
const result = await FormData.postFormsData({
formIdentifier: 'contact_us',
formData,
formModuleConfigId: moduleConfig?.id || 0,
moduleEntityIdentifier: moduleConfig?.entityIdentifiers?.[0]?.id || '',
replayTo: null,
status: 'sent',
});
if ('statusCode' in result) {
setErrorMsg(result.message || 'Submission failed');
setStatus('error');
} else {
setStatus('success');
console.log('Submit result: ', result);
}
};
return (
<form onSubmit={handleSubmit}>
<h2>{form.localizeInfos?.title || 'Contact Form'}</h2>
{sortedFields.map((field: any) => {
const label = field.localizeInfos?.title || field.marker;
const value = values[field.marker] || '';
const required = !!field.validators?.requiredValidator?.strict;
const placeholder = field.additionalFields?.placeholder?.value || '';
const onChange = (val: string) =>
setValues((prev) => ({ ...prev, [field.marker]: val }));
if (field.type === 'text') {
return (
<div key={field.marker}>
<label htmlFor={field.marker}>{label}</label>
<textarea
id={field.marker}
value={value}
placeholder={placeholder}
required={required}
onChange={(e: { target: { value: string; }; }) => onChange(e.target.value)}
/>
</div>
);
}
if (field.type === 'list') {
return (
<div key={field.marker}>
<label htmlFor={field.marker}>{label}</label>
<select
id={field.marker}
value={value}
required={required}
onChange={(e: { target: { value: string; }; }) => onChange(e.target.value)}
>
<option value="">— Select —</option>
{(field.listTitles || []).map((opt: any) => (
<option key={opt.value} value={opt.value}>{opt.title}</option>
))}
</select>
</div>
);
}
if (field.type === 'radioButton') {
return (
<fieldset key={field.marker}>
<legend>{label}</legend>
{(field.listTitles || []).map((opt: any) => (
<label key={opt.value}>
<input
type="radio"
name={field.marker}
value={opt.value}
checked={value === opt.value}
onChange={() => onChange(opt.value)}
/>
{opt.title}
</label>
))}
</fieldset>
);
}
if (field.type === 'button') {
return (
<button
key={field.marker}
type="submit"
disabled={status === 'loading'}
>
{label}
</button>
);
}
return (
<div key={field.marker}>
<label htmlFor={field.marker}>{label}</label>
<input
id={field.marker}
type={typeMap[field.type] || 'text'}
value={value}
placeholder={placeholder}
required={required}
onChange={(e: { target: { value: string; }; }) => onChange(e.target.value)}
/>
</div>
);
})}
{status === 'error' && <p role="alert">{errorMsg}</p>}
{status === 'success' && <p role="status">Form submitted successfully!</p>}
</form>
);
};
export default ContactForm;