Try our conversational search powered by Generative AI!

Allan Thraen
Jul 27, 2016
  2977
(1 votes)

Mandatory form fields in all forms on site

Recently I got a few questions on how to enforce that all forms (based on Episerver Forms) on a site includes certain elements. This can be useful, if you for instance always want to make sure the right fields get pushed onwards to your Marketing Automation system. So, I wrote a few lines of code and figure I'd share them here for everybody to enjoy.

The basic approach I've taken is to 1) ensure the fields are automatically added whenever a form is created, 2) ensure that no form can be published without the fields on it.

It's all done in one initialization class, using the fact that forms are just like any other block.

Enjoy!

 

using System;
using System.Linq;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.Core;
using EPiServer;
using EPiServer.Forms.Implementation.Elements;

namespace FormsExamples.FormExtension.MandatoryFields
{
    [InitializableModule]
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class MandatoryFieldsInit : IInitializableModule
    {

        /*
         * Ensure all forms has a ContactName field.
         * 
         * */

        private IContentRepository repo;
        private ContentAssetHelper assethelper;

        public void Initialize(InitializationEngine context)
        {
            //Add initialization logic, this method is called once after CMS has been initialized
            context.InitComplete += Context_InitComplete;
        }

        private void Context_InitComplete(object sender, EventArgs e)
        {
            var evnts = ServiceLocator.Current.GetInstance();
            assethelper = ServiceLocator.Current.GetInstance();
            repo = ServiceLocator.Current.GetInstance();
            evnts.CreatedContent += Evnts_CreatedContent;
            evnts.PublishingContent += Evnts_PublishingContent;
            evnts.CheckingInContent += Evnts_CheckingInContent;
        }

        private void Evnts_CheckingInContent(object sender, ContentEventArgs e)
        {
            if (e.Content is EPiServer.Forms.Implementation.Elements.FormContainerBlock)
            {
                //Validate that it contains the mandatory fields
                var container = e.Content as EPiServer.Forms.Implementation.Elements.FormContainerBlock;
                if ((container.ElementsArea == null) || (!container.ElementsArea.Items.Where(cai => cai.GetContent().Name == "ContactName").Any()))
                {
                    throw new EPiServerException("You are required to include a field named ContactName in all forms");

                }
            }
        }

        private void Evnts_PublishingContent(object sender, ContentEventArgs e)
        {
            if (e.Content is EPiServer.Forms.Implementation.Elements.FormContainerBlock)
            {
                //Validate that it contains the mandatory fields
                var container = e.Content as EPiServer.Forms.Implementation.Elements.FormContainerBlock;
                if ((container.ElementsArea == null) || (!container.ElementsArea.Items.Where(cai => cai.GetContent().Name == "ContactName").Any()))
                {
                    throw new EPiServerException("You are required to include a field named ContactName in all forms");

                }
            }
        }


        private void Evnts_CreatedContent(object sender, EPiServer.ContentEventArgs e)
        {
            if (e.Content is EPiServer.Forms.Implementation.Elements.FormContainerBlock)
            {
                //Create mandatory fields and add them to the form
                var folder = assethelper.GetOrCreateAssetFolder(e.ContentLink); //Forcing a save
                TextboxElementBlock teb = repo.GetDefault(folder.ContentLink);
                (teb as IContent).Name = "ContactName";
                teb.Label = "Contact Name";
                var nameref=repo.Save(teb as IContent, EPiServer.DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);
                //Get writeable version of the current form container
                var clone = (e.Content as EPiServer.Forms.Implementation.Elements.FormContainerBlock).CreateWritableClone() as FormContainerBlock;
                //Ensure we have a content area
                if (clone.ElementsArea == null)
                {
                    clone.ElementsArea = new ContentArea();
                }
                //Add field to contentarea
                clone.ElementsArea.Items.Add(new ContentAreaItem() { ContentLink = nameref });
                //Save it
                repo.Save((IContent) clone, EPiServer.DataAccess.SaveAction.Save, EPiServer.Security.AccessLevel.NoAccess);


            }
        }

        public void Uninitialize(InitializationEngine context)
        {
            //Add uninitialization logic
        }
    }
}
Jul 27, 2016

Comments

Matt Schiller
Matt Schiller Aug 1, 2016 07:25 PM

Is there any way to apply permissions to the programmatically added fields so that only certain groups can make edits or change / delete them?

Please login to comment.
Latest blogs
Configured Commerce - Infrastructure Updates Ahoy!

I'm very happy to share an important milestone - we no longer have any customers in our legacy v1 environment!  This means that the Configured...

John McCarroll | May 10, 2024

A day in the life of an Optimizely Developer - Enabling Opti ID within your application

Hello and welcome to another instalment of A Day In The Life Of An Optimizely developer, in this blog post I will provide details on Optimizely's...

Graham Carr | May 9, 2024

How to add a custom property in Optimizely Graph

In the Optimizely CMS content can be synchronized to the Optimizely Graph service for it then to be exposed by the GraphQL API. In some cases, you...

Ynze | May 9, 2024 | Syndicated blog

New Security Improvement released for Optimizely CMS 11

A new security improvement has been released for Optimizely CMS 11. You should update now!

Tomas Hensrud Gulla | May 7, 2024 | Syndicated blog