Calling all developers! We invite you to provide your input on Feature Experimentation by completing this brief survey.

 

Allan Thraen
Jul 27, 2016
  3133
(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
Level Up with Optimizely's Newly Relaunched Certifications!

We're thrilled to announce the relaunch of our Optimizely Certifications—designed to help partners, customers, and developers redefine what it mean...

Satata Satez | Jan 14, 2025

Introducing AI Assistance for DBLocalizationProvider

The LocalizationProvider for Optimizely has long been a powerful tool for enhancing the localization capabilities of Optimizely CMS. Designed to ma...

Luc Gosso (MVP) | Jan 14, 2025 | Syndicated blog

Order tabs with drag and drop - Blazor

I have started to play around a little with Blazor and the best way to learn is to reimplement some old stuff for CMS12. So I took a look at my old...

Per Nergård | Jan 14, 2025

Product Recommendations - Common Pitfalls

With the added freedom and flexibility that the release of the self-service widgets feature for Product Recommendations provides you as...

Dylan Walker | Jan 14, 2025