Enviar um formulário
Carrega os campos de um formulário, renderiza-os e envia os dados do usuário com FormData.postFormsData().
O que este exemplo faz:
- Obtém a configuração do formulário na OneEntry Platform
- Coleta os dados informados pelo usuário em um formulário de contato.
- Converte cada valor para o formato esperado pelo tipo do seu campo (veja prepareValue()).
- Envia os dados coletados para a API do OneEntry.
Pré-requisitos:
- Um PROJECT_URL e um APP_TOKEN válidos para a API do OneEntry.
- Um formulário no OneEntry identificado por um marcador (ex.: 'contact_us').
- Campos configurados nesse formulário (este exemplo trata campos string, text, list, radioButton e button).
Observações:
- Trate os erros da API e mostre um retorno aos usuários.
- Mantenha os campos do formulário e seus marcadores sincronizados com a configuração do backend.
- Por padrão (
isShell: true), o SDK retorna um objeto de erro em vez de lançar uma exceção, então verifique o resultado, por exemplo'statusCode' in result. ComisShell: false, ele lança a exceção, e você trata os erros com try/catch. Veja Erros.
Documentação da plataforma:
Referência do SDK:
Experimente ao vivo
Execute este exemplo no sandbox do JS SDK. Conecte a URL do seu projeto e o App Token na primeira visita e, em seguida, abra:
Cenário
1. Importar defineOneEntry e definir PROJECT_URL e APP_TOKEN
import { defineOneEntry } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
2. Criar um cliente da API com defineOneEntry()
const { Forms, FormData } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. Obter o formulário com 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. Ler a configuração de módulos do formulário
postFormsData() precisa do id da configuração (formModuleConfigId) e do identificador da entidade à qual o formulário está vinculado (moduleEntityIdentifier). Ambos vêm de form.moduleFormConfigs.
const moduleConfig = form.moduleFormConfigs?.[0];
const sortedFields = [...(form.attributes || [])].sort(
(a: any, b: any) => a.position - b.position,
);
5. Obter os dados dos campos do formulário do 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 os dados do formulário com 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"
}
Exemplo 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;