Get Specific Elements Blocks from EPiServer Forms

A small extension to get the specific form elements block with all properties rather relying on  FriendlyNameInfo with the limited set of properties.


Example:
Custom form element block:
public class HiddenExternalValueElementBlock : HiddenElementBlockBase
{
    [Display(Name = "Enable if its a special campaign")]
    public virtual bool MySpecialCampaign { getset; }

    [Display(Name = "Propperty 1")]
    public virtual bool Property1 { getset; }

    [Display(Name = "Property 2")]
    public virtual bool Property2 { getset; }
}

Extension Methods:
using EPiServer.Core;
using EPiServer.Forms.Core;
using EPiServer.Forms.Core.Models;
using EPiServer.Forms.Helpers.Internal;
using EPiServer.Forms.Implementation.Elements;
using System.Collections.Generic;
using System.Linq;
 
namespace PixieDigital.EpiServer.Extensions
{
    public static class FormExtensions
    {
        public static IEnumerable<T> GetSpecificFormElements<T>(this FormIdentity formIdentity, bool filteredItemsOnly = truewhere T : ElementBlockBase
        {
            return GetSpecificFormElements<T>(formIdentity.GetFormBlock(), filteredItemsOnly);
        }
 
        public static IEnumerable<T> GetSpecificFormElements<T>(this FormContainerBlock formContainerBlock, bool filteredItemsOnly = truewhere T : ElementBlockBase
        {
            if (formContainerBlock != null && formContainerBlock.ElementsArea != null && formContainerBlock.ElementsArea.Items != null && formContainerBlock.ElementsArea.Items.Count() != 0)
            {
                var formElements = filteredItemsOnly ? formContainerBlock.ElementsArea.FilteredItems : formContainerBlock.ElementsArea.Items;
 
                foreach (var item in formElements)
                {
                    T element = item.ContentLink.GetContent((formContainerBlock as ILocale).Language.Name) as T;
                    if (element != null)
                    {
                        yield return element;
                    }
                }
            }
        }
    }
}

Usage:
Guid formGuid = "xxx-xx-xxxx";
var formIdentity = new FormIdentity(formGuid, "en");
var hiddenElement = formIdentity.GetSpecificFormElements<HiddenExternalValueElementBlock>();
//Use it for further processing
var formId = hiddenElement.FirstOrDefault().Content.ContentLink.GetElementName();
var definedElementName = hiddenElement.FirstOrDefault().Content.Name;
var mySpecialCampaign = hiddenElement.FirstOrDefault().MySpecialCampaign;                        

Comments

Popular posts from this blog

EPiServer CMS 11 Useful SQL Queries - 1

EPiServer CMS 11 Useful SQL Queries - 2

Strongly Type Models in EPiServer Commerce