Enviar un formulario con un campo entity
Envía un formulario que incluye un campo de tipo entidad, como páginas o productos.
Qué hace este ejemplo:
- Obtiene la configuración del formulario desde OneEntry.
- El usuario selecciona uno de los elementos de la entidad
- 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 con el marcador "entity" que tenga al menos un campo de tipo "entity".
Notas:
- 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('entity').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');
});
}, []);
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 moduleFormConfig = form.moduleFormConfigs?.[0];
if (!moduleFormConfig) {
setErrorMsg('Form has no moduleFormConfigs');
setStatus('error');
return;
}
Resultado:
{
"id": 1,
"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
}
5. Recoger los valores de los campos del formulario
Para cada campo de entidad, envía el id de la opción que eligió el usuario (un id de página o un id de producto como "p-1-123").
const fieldsData = 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": "entity",
"type": "entity",
"value": [
"p-2-7"
]
}
]
6. Enviar los datos del formulario con FormData.postFormsData()
const response = await FormData.postFormsData({
formIdentifier: 'entity',
formData: fieldsData,
formModuleConfigId: moduleFormConfig.id,
moduleEntityIdentifier: moduleFormConfig.entityIdentifiers?.[0]?.id || '',
replayTo: null,
status: 'sent',
});
Resultado:
{
"formData": {
"formIdentifier": "entity",
"time": "2026-06-06T10:21:42.166Z",
"formData": [
{
"marker": "entity",
"type": "entity",
"value": [
"p-2-7"
]
}
],
"entityIdentifier": "services",
"fingerprint": "UQ_zhfcsr_mpdtr691jq7d",
"isUserAdmin": false,
"formModuleId": 1,
"userIdentifier": null,
"parentId": null,
"id": 174
},
"actionMessage": ""
}
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];
if (type === 'entity') return [/^\d+$/.test(value) ? Number(value) : value];
return value;
}
const EntityForm = () => {
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('entity').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 moduleFormConfig = form.moduleFormConfigs?.[0];
if (!moduleFormConfig) {
setErrorMsg('Form has no moduleFormConfigs');
setStatus('error');
return;
}
// 5. Collect field values from the form
const fieldsData = sortedFields
.filter((f: any) => values[f.marker] !== '')
.map((f: any) => ({
marker: f.marker,
type: f.type,
value: prepareValue(f.type, values[f.marker] ?? ''),
}));
// 6. Post form data with FormData.postFormsData()
const response = await FormData.postFormsData({
formIdentifier: 'entity',
formData: fieldsData,
formModuleConfigId: moduleFormConfig.id,
moduleEntityIdentifier: moduleFormConfig.entityIdentifiers?.[0]?.id || '',
replayTo: null,
status: 'sent',
});
if ('statusCode' in response) {
setErrorMsg(response.message || 'Submission failed');
setStatus('error');
} else {
setStatus('success');
console.log('Submit response: ', response);
}
};
return (
<form onSubmit={handleSubmit}>
<h2>{form.localizeInfos?.title || 'Entity 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 === 'entity') {
const options = field.listTitles || [];
if (options.length > 0) {
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>
{options.map((opt: any) => {
// For entity fields, listTitles[].value is an object ({ id, depth, ... }),
// so use its primitive `id` for the key/value (a page id like 25 or product like "p-1-123").
const optValue = opt.value && typeof opt.value === 'object' ? opt.value.id : opt.value;
return (
<option key={optValue} value={optValue}>{opt.title}</option>
);
})}
</select>
</div>
);
}
return (
<div key={field.marker}>
<label htmlFor={field.marker}>{label}</label>
<input
id={field.marker}
type="text"
value={value}
placeholder={placeholder || 'Page id (e.g. 25) or product (e.g. p-1-123)'}
required={required}
onChange={(e: { target: { value: string; }; }) => onChange(e.target.value)}
/>
</div>
);
}
return (
<div key={field.marker}>
<label htmlFor={field.marker}>{label}</label>
<input
id={field.marker}
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>}
<button type="submit" disabled={status === 'loading'}>
{status === 'loading' ? 'Submitting...' : 'Submit'}
</button>
</form>
);
};
export default EntityForm;