Wednesday 22 March 2023

Custom Form Elements in Headless (JSS) Forms

I've been getting pretty deep into the Sitecore React/Next.JS Forms libraries over the last couple of weeks, and while there's some half decent information out there if you look hard enough, it's generally not that accessible or complete. For example, one of the better pages altering field types is hidden away in GitHub and doesn't seem to pop up for me in a Google search.

I find that Sitecore Forms, while a great form builder, still lacks (at least) a couple of fields which I would consider a must-have: hidden fields, and raw HTML. Fortunately these can be found in Sitecore Forms Extensions, so we can copy the relevant code from there.

Once you've got the fields into Sitecore - in the form builder and rendering their properties into the layout service - the next step is to ensure your React/Next.JS code knows how to render the fields. Fortunately per the link above, this is fairly easy to inject/extend using a custom field factory:

We can then add our custom field factory to our form, and we should be good to go!

<Form
  form={fields}
  sitecoreApiHost={process.env.SITECORE_API_HOST}
  sitecoreApiKey={process.env.SITECORE_API_KEY}
  onRedirect={(url: string) => router.push(url)}
  fieldFactory={CustomFieldFactory}
/>

Issues / wish list:

  • CustomFieldFactory.setComponent first parameter relies on the FieldTypes enum (but works with any string). This causes Typescript errors. It would be great if this parameter/enum were extendable.
  • The Form component extends Component<FormProps, FormState & FieldStateCollection> but is itself not generic! This means that props can't be overridden, which means adding custom properties causes Typescript errors (though the code still works). Ideally Form would be generic so that we could pass custom props and properly override the Form class.
  • Conditions are not included anywhere in the Sitecore Forms React code :( See an upcoming post for how we can achieve conditional logic using OOTB Sitecore Forms conditions.
  • There is no validation on form submission! This was very surprising (and frustrating) to find (and implement).
  • There is no validation for mandatory fields on a couple of fields, eg. CheckboxList
  • Fields are still submitted by the JSS code even when adding a 'disabled' attribute to the field. This super painful to work around!

No comments:

Post a Comment