November Happy Hour will be moved to Thursday December 5th.

Allan Thraen
Jul 27, 2016
  3103
(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
Adding Geolocation Personalisation to Optimizely CMS with Cloudflare

Enhance your Optimizely CMS personalisation by integrating Cloudflare's geolocation headers. Learn how my Cloudflare Geo-location Criteria package...

Andy Blyth | Nov 26, 2024 | Syndicated blog

Optimizely SaaS CMS + Coveo Search Page

Short on time but need a listing feature with filters, pagination, and sorting? Create a fully functional Coveo-powered search page driven by data...

Damian Smutek | Nov 21, 2024 | Syndicated blog

Optimizely SaaS CMS DAM Picker (Interim)

Simplify your Optimizely SaaS CMS workflow with the Interim DAM Picker Chrome extension. Seamlessly integrate your DAM system, streamlining asset...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Optimizely CMS Roadmap

Explore Optimizely CMS's latest roadmap, packed with developer-focused updates. From SaaS speed to Visual Builder enhancements, developer tooling...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Set Default Culture in Optimizely CMS 12

Take control over culture-specific operations like date and time formatting.

Tomas Hensrud Gulla | Nov 15, 2024 | Syndicated blog

I'm running Optimizely CMS on .NET 9!

It works 🎉

Tomas Hensrud Gulla | Nov 12, 2024 | Syndicated blog