Skip to content

Commit

Permalink
feat: allow form block to submit to an arbitraty url
Browse files Browse the repository at this point in the history
  • Loading branch information
shsteimer committed Jun 24, 2024
1 parent b8e26a5 commit 9e55017
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions blocks/form/form.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import createField from './form-fields.js';
import { sampleRUM } from '../../scripts/aem.js';

async function createForm(formHref) {
async function createForm(formHref, submitHref) {
const { pathname } = new URL(formHref);
const resp = await fetch(pathname);
const json = await resp.json();

const form = document.createElement('form');
// eslint-disable-next-line prefer-destructuring
form.dataset.action = pathname.split('.json')[0];
form.dataset.action = submitHref;

const fields = await Promise.all(json.data.map((fd) => createField(fd, form)));
fields.forEach((field) => {
Expand Down Expand Up @@ -86,10 +86,12 @@ async function handleSubmit(form) {
}

export default async function decorate(block) {
const formLink = block.querySelector('a[href$=".json"]');
const links = [...block.querySelectorAll('a')].map((a) => a.href);
const formLink = links.find((link) => link.startsWith(window.location.origin) && link.endsWith('.json'));
const submitLink = links.find((link) => link !== formLink);
if (!formLink) return;

const form = await createForm(formLink.href);
const form = await createForm(formLink, submitLink);
block.replaceChildren(form);

form.addEventListener('submit', (e) => {
Expand Down

0 comments on commit 9e55017

Please sign in to comment.