Sitecore Forms : Custom Submit Action to Create and Publish Content Item(Part 1)

 

Problem

I encountered a situation that the website was internally facing, which needed a form that would not save the data in the Experience Forms database. Also the data needs to be saved as an Item in the master database so it could be published and consumed in a listing page.

At first, I considered creating a Custom Submit Action to create and publish an item. However, I later realized that the CD server lacked access to the CM server, preventing it from directly generating an item in the master database. So, I came up with the idea of creating a custom API service and combining it with a custom submit action.

Solution

To implement this followed this process

  • Create Custom Submit Action in Sitecore
  • Create a code-behind class that inherits SubmitActionBase
  • Create a secure API that can create and publish an item
  • Create an API authorization user in the identity server 
  • Create a Controller to proxy between Custom Submit Action and API calls
  • Set the Custom Submit Action fields

 

1. Custom Submit Action in Sitecore

Create the custom submit action in the following path /sitecore/system/Settings/Forms/Submit Actions.

Sitecore_Forms_1.png

 

2. Create a code-behind class that inherits SubmitActionBase

Create a class that inherits the SubmitActionBase class and overrides the Execute method which calls the API asynchronously to create and publish an item.

The CreateAndAutoPublish class extends SubmitActionBase<string> and is designed to handle form submissions in Sitecore, creating and auto-publishing content items.

It uses dependency injection to obtain instances of IHttpClientFactoryBaseSettings, and ISitecoreRestServices, which are lazily initialized. The ExecuteAction method validates the form submission context and parameters, then calls the Execute method to prepare a model from form fields, serialize it to JSON, and send it to a Sitecore API endpoint using an HTTP POST request.

The class includes helper methods to extract values from form fields and handles errors by logging them and adding them to the form submission context’s error collection.

 

3. Create an API call that creates and publishes the item  

The API call does the following things – 

  1. Creates an item under a specified folder
  2. Move and Sync the item into a bucket
  3. Publish the item
  4. Clear the Sitecore cache
  5. Ensure the published item is indexed or force index the item
  6. Clear the Vercel Cache for frontend

In Part 2, we will see how to

  • Create an API authorization user in the identity server 
  • Create a Controller to proxy between Custom Submit Action and API calls
  • Set the Custom Submit Action fields

Hope this helps.

Happy Sitecoring!

1 Response

Leave a Reply

Your email address will not be published. Required fields are marked *