Headless submissions via custom REST API / PHP? #2034
-
Hi, I'm researching for the following use case:
I know, Formie has good GraphQL support - but in the use case we would like to do it via REST API. I also know there are some things like Controller Actions - but haven't found an info about this in Formie docs. Is there a quick way to achieve sending POST data, return validation object - or successful response when submission was made and is stored in Formie? Thx in advance for any hints! Best regards, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The best method is to use GraphQL mutations for headless, but using REST is also possible. Your best bet is to mimic a POST submission just like a traditional form would. We don't have docs about this, purely because it's very straightforward to create a Twig template, render your form, test submission and inspect the payload sent to the server. So long as you copy that, you're fine. For example: // Method 1: construct an object of data
var body = {
"action": "formie/submissions/submit",
"handle": "contactForm",
"siteId": "1",
"fields[yourName]": "dave",
"fields[emailAddress]": "[email protected]",
"fields[message]": "this is a message",
};
// Append CSRF token
window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";
body[window.csrfTokenName] = window.csrfTokenValue;
fetch('/', {
method: 'post',
body: body,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
},
}).then(function(response) {
response.json().then(function(data) {
console.log(data);
});
})
// Method 2: construct from a form, using FormData
let formElem = document.getElementById('form');
let data = new FormData(formElem);
fetch('/', {
method: 'post',
body: data,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
},
}).then(function(response) {
response.json().then(function(data) {
console.log(data);
});
}) But because you're doing all the submitting on your own, you're going to need to handle things like captchas on your own, such as reCAPTCHA and append those to the payload. |
Beta Was this translation helpful? Give feedback.
The best method is to use GraphQL mutations for headless, but using REST is also possible. Your best bet is to mimic a POST submission just like a traditional form would. We don't have docs about this, purely because it's very straightforward to create a Twig template, render your form, test submission and inspect the payload sent to the server. So long as you copy that, you're fine.
For example: