Extending SitecoreAI Forms with Sitecore Managed Email Configuration

Sumit Bhatia

Extending SitecoreAI Forms with Sitecore Managed Email Configuration

SitecoreAI Forms comes with all the functionality out of the box that handles almost everything where authors can build a form, drop it on a page and start collecting submissions without a developer getting involved. But there are a few things that can’t be done with out of the box features and Sitecore doesn’t recommend doing any kind of customization. So in this blog I will describe a scenario where while migrating from Sitecore XP to SitecoreAI, we need to carry over the same functionality and what I did without customizing anything.

Requirement

In the legacy XP version of the project, the client had configured email configurations by adding custom fields in Sitecore forms to allow content authors to enter email subject, body and recipient names, and when the form gets submitted, a custom submit action gets all the values and sends the email using a third party API.

Also they have options for content authors where they can bind radio button list, dropdown box etc. kind of selection boxes with some datasource. And each content item has an email configured. So if a user selects any option using these fields then the email should also go to that recipient.

Limitations in SitecoreAI Forms

There are a few limitations in SitecoreAI for now, that couldn’t fit the legacy functionality.

  1. It doesn’t have options to add custom fields for content authors to enter email information like subject, recipient and body.
  2. Doesn’t allow content authors to bind a dropdown, radio button list with content items. Because you can’t access Sitecore content tree on SitecoreAI Forms.
  3. No custom submit action, so we can’t get all the email configuration on submit.
  4. SitecoreAI form rendering clone doesn’t work. (Already raised a feature request for this)

So to make it work, we need to configure a few things in SitecoreAI, so the functionality can be easily achieved.

How it fits with SitecoreAI

There are a few things that I configured in SitecoreAI to achieve this functionality. Here they are:

  1. Form Wrapper: I created a new component called FormWrapper that comes with a placeholder, allows content authors to drop in a form. The idea is to add some rendering parameters on the wrapper component that can allow content authors to enter email body, subject and recipients. The author drops the OOTB form component into the wrapper’s placeholder, the same way they would anywhere else.

  2. A blank field called “ID” that should be hidden, on each form that will be used to fill by item ID when the page renders. This will be used to get the values of rendering parameters on the submit.

  3. When a visitor submits the form using the webhook, along with all the fields we get the ID field of the page. Using graphQLRequestClient we can get the details of email (subject, recipient and body) and then using a third-party API or code, we can send the email.

  4. To bind the dropdown or radio button, in SitecoreAI Forms we can either create items using key value pair or we can call an API that can get a JSON response to bind that. So we created an API that can be used to get all the child items of a parent by passing parent item ID as a query string parameter. Use this API to get the item name and ID on the dropdown list and radio button list.

    When a user selects any item from the dropdown or radio button, get the ID of the selected item and using graphQLRequestClient fetch the details of the item like recipient email and send email to those as well.

This way we achieved the same functionality without modifying anything on the SitecoreAI side.

Part 1: The FormWrapper component

The wrapper is a JSON rendering with a placeholder for the form and a rendering parameters template with three fields: To, Subject and Body. Authors fill these in from the component’s settings in Pages, so each form on each page can send a different email.

On the Sitecore side you need:

  1. A rendering parameters template with To, Subject and Body fields.
  2. A JSON rendering for the wrapper that uses that template.
  3. A dynamic placeholder, PlaceholderForm-{*}, with placeholder settings that only allow the OOTB form component.

In Next.js, the parameters arrive on props.params like any other rendering parameter:

interface FormWrapperProps {
  rendering: { uid: string; componentName: string; dataSource: string };
  params?: {
    Body?: string;
    styles?: string;
    RenderingIdentifier?: string;
    [key: string]: string | undefined;
  };
}

The form first loads as plain HTML. Then Sitecore’s scripts add extra features on top, like the phone number box, field validation and show/hide rules. If React re-renders the placeholder, it puts the plain HTML back and those features are lost. To stop this, we wrapped the placeholder in memo, so it only re-renders when the rendering UID changes:

const StablePlaceholder = memo(
  ({ rendering }: { rendering: FormWrapperProps['rendering'] }) => (
    <Placeholder name="PlaceholderForm-{*}" rendering={rendering} editable />
  ),
  (prev, next) => prev.rendering.uid === next.rendering.uid
);

Part 2: The hidden pageid field

The webhook only receives what’s in the form, so the form has the ID of the page it was rendered on. Every form gets a hidden field named pageid. The author adds it once in the form builder and leaves it empty. The wrapper fills it in when the page renders.

Later the field is set with a small JSON string with three values: the wrapper’s rendering UID, the site name and the item path. These fields will be used to get data from Sitecore.

const emailDataJson = useMemo(
  () =>
    JSON.stringify({
      renderingUid: rendering.uid,
      siteName: page?.layout?.sitecore?.context?.site?.name,
      itemPath: page?.layout?.sitecore?.context?.itemPath || '',
    }),
  [rendering.uid, page?.layout?.sitecore?.context?.site?.name, page?.layout?.sitecore?.context?.itemPath]
);

The thing to consider is the timing to mount. The form’s HTML is injected after React has rendered, so the hidden input isn’t there when the component mounts. A MutationObserver watches the wrapper, writes the value as soon as the input appears and then disconnects:

useEffect(() => {
  if (!formBody || !sdkReady) return;
  const container = containerRef.current;
  if (!container) return;

  let observer: MutationObserver | null = null;

  const trySetPageId = () => {
    const input = container.querySelector<HTMLInputElement>('input[name="pageid"]');
    if (!input) return;
    input.value = emailDataJson;
    input.dispatchEvent(new Event('input', { bubbles: true }));
    observer?.disconnect();
    observer = null;
  };

  // Give Sitecore's own scripts a chance to bind first
  const rafId = requestAnimationFrame(() => setTimeout(trySetPageId, 0));

  observer = new MutationObserver(trySetPageId);
  observer.observe(container, { childList: true, subtree: true });

  return () => {
    cancelAnimationFrame(rafId);
    observer?.disconnect();
  };
}, [formBody, sdkReady, emailDataJson]);

Part 3: The webhook API route

In the SitecoreAI Forms, point the form’s webhook at a Next.js API route. We called it send-form-email. When a visitor submits, the route receives every field, including pageid, and does three things.

First, it reads pageid and asks Sitecore for that wrapper’s rendering parameters. fetchRenderingParams is our own helper. It runs a layout query through graphQLRequestClient for the item path and site, then finds the rendering with the matching UID and returns its parameters.

async function extractEmailParams(body: Record<string, unknown>): Promise<EmailParams> {
  const { renderingUid, siteName, itemPath } = extractPageIdConfig(body);

  if (!renderingUid || !siteName || !itemPath) {
    throw new Error('Missing rendering information in pageid');
  }

  const params = await fetchRenderingParams(siteName, itemPath, renderingUid, 'en');

  if (!params?.To || !params?.Subject) {
    throw new Error('Email configuration not found. Check the wrapper has To and Subject set.');
  }

  return { To: params.To, Subject: params.Subject, Body: params.Body, From: DEFAULT_FROM_EMAIL };
}
  • Second, it gets the form values ready for the email. normalizeFormData makes the values easy to read, for example

    First Name: John
    Email: [email protected]
  • buildEmailPayload adds those answers into the subject and body the author wrote, so the email is ready to send.

Third, it sends the email. We post to an internal email service, but any provider works here.

const emailParams = await extractEmailParams(rawBody);
const normalizedFormData = await normalizeFormData(extractFormData(rawBody));

if (Object.keys(normalizedFormData).length === 0) {
  return res.status(400).json({ success: false, message: 'Form data is missing.' });
}

const emailPayload = await buildEmailPayload(normalizedFormData, emailParams, DEFAULT_FROM_EMAIL);

const emailResponse = await fetch(process.env.EMAIL_API_URL!, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(emailPayload),
});

Part 4: Dropdowns and radio buttons that route the email

SitecoreAI Forms gives you two ways to fill a dropdown or radio list. You can type key/value pairs into the form builder, or you can point the field at an API that returns JSON. We went with the API, because the options already existed as content items and each one needed its own recipient.

The child items API

The API takes a parent item ID in the query string and returns that item’s children as name and ID pairs. The form builder calls it to fill the field, so the visible label is the item name and the submitted value is the item ID.

// /api/child-items?parentId={GUID}
const query = `
  query ($parentId: String!) {
    item(path: $parentId, language: "en") {
      children { results { id name } }
    }
  }`;

const data = await graphQLRequestClient.request(query, { parentId });
const options = data.item.children.results.map((c) => ({ text: c.name, value: c.id }));

res.status(200).json(options);

With this in place, a new department or location is just a new child item. Nobody has to edit the form.

Sending to the selected item’s recipient

Since the submitted value is an item ID, the webhook route can look that item up and read its recipient field. Those addresses get added to the To list from the wrapper.

const selectedId = normalizedFormData['Department'];

if (selectedId) {
  const item = await graphQLRequestClient.request(RECIPIENT_QUERY, { id: selectedId });
  const extra = item?.item?.recipient?.value;
  if (extra) emailParams.To = `${emailParams.To};${extra}`;
}

One thing to add before going live: check that the submitted ID really is a child of the parent the field was bound to. Otherwise someone could post any item ID they like and the route would happily read it.

Challenges We Faced

  • Form stopped working after re-rendering: Whenever the component re-rendered, the form HTML loaded again. Because of this, the phone number field and validation stopped working. We fixed this using the approach explained in Part 1.
  • Hidden field was getting an empty value: We were setting the value before the hidden field was available on the page. To fix this, we added an observer in Part 2 that waits for the field to appear before setting its value.
  • Form fields were still showing after submission: After submitting the form, Sitecore displayed a success or error popup, but the form fields were still visible. We added another observer to detect the popup and hide the form fields while keeping the button area in place.
  • Changes were not showing until publishing: When we updated the To or Subject values in the rendering parameters, the changes didn’t appear immediately. We had to publish the page to see the updated values. So, if emails are going to the wrong address, first check whether the latest changes are published.
  • Keep sensitive information on the server: Email API URLs and secret keys should be stored in server-side environment variables. Avoid using NEXT_PUBLIC_ for sensitive values because these variables can be accessed from the browser.

Wrapping up

The whole setup is one wrapper component, one hidden field, one webhook route and one small API for list options. Authors control who gets each email and what it says, and adding a new recipient to a dropdown is a content change. The OOTB form stays exactly as Sitecore ships it, so the next platform update doesn’t touch any of this.