Allan Thraen
Jul 27, 2016
  3060
(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
Integrating Optimizely DAM with Your Website

This article is the second in a series about integrating Optimizely DAM with websites. It discusses how to install the necessary package and code t...

Andrew Markham | Sep 28, 2024 | Syndicated blog

Opticon 2024 - highlights

I went to Opticon in Stockholm and here are my brief highlights based on the demos, presentations and roadmaps  Optimizely CMS SaaS will start to...

Daniel Ovaska | Sep 27, 2024

Required fields support in Optimizely Graph

It's been possible to have "required" properties (value must be entered) in the CMS for a long time. The required metadata haven't been reflected i...

Jonas Bergqvist | Sep 25, 2024

How to write a bespoke notification management system

Websites can be the perfect vehicle for notifying customers of important information quickly, whether it’s the latest offer, an operational message...

Nicole Drath | Sep 25, 2024

Optimizely DAM – An Introduction

I presented a talk about the Optimizely DAM at the OMVP summit during Opticon 2024 in Sweden. I have now converted that talk into two blog posts....

Andrew Markham | Sep 25, 2024 | Syndicated blog

Simple and Effective Personalization with Optimizely Data Platform (ODP)

As we dive into the amazing capabilities of Optimizely One, let’s shine a spotlight on the Optimizely Data Platform (ODP). This simple tool unifies...

Alex Harris - Perficient | Sep 24, 2024 | Syndicated blog