Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

Allan Thraen
Jul 27, 2016
  2967
(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
Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024

Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog