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 { get; set; }
[Display(Name = "Propperty 1")] public virtual bool Property1 { get; set; }[Display(Name = "Property 2")] public virtual bool Property2 { get; set; }}
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 = true) where T : ElementBlockBase { return GetSpecificFormElements<T>(formIdentity.GetFormBlock(), filteredItemsOnly); } public static IEnumerable<T> GetSpecificFormElements<T>(this FormContainerBlock formContainerBlock, bool filteredItemsOnly = true) where 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
Post a Comment