blipson89 / Synthesis

Synthesis is a universal object mapper for Sitecore
MIT License
75 stars 25 forks source link

Add Synthesis Rendering Parameters Helper #85

Open blipson89 opened 5 years ago

blipson89 commented 5 years ago

Consider adding Jose's rendering parameters helper to the core API: https://josedbaez.com/2016/09/synthesis-rendering-parameters-helper/

kukens commented 5 years ago

Hi Ben

I was basing on Jose's helper in some project with small modifications. Instead of supplying the template id as a parameter to GetRenderingParameters method, I have extracted it automatically from type's attributes using reflection (first two lines below):

public TTemplate GetRenderingParameters<TTemplate>() where TTemplate : class, IStandardRenderingParametersItem
        {
            var sitecoreTemplateAttribute =typeof(TTemplate).GetCustomAttributes(typeof(RepresentsSitecoreTemplateAttribute), false).FirstOrDefault() as RepresentsSitecoreTemplateAttribute;
            var templateID = ID.Parse(sitecoreTemplateAttribute?.TemplateId) ?? ID.NewID;

            var itemDefinition = new ItemDefinition(ID.NewID, "renderingparamitem", templateID, ID.Null);
            var itemData = new ItemData(itemDefinition, Context.Language, Context.Item.Version, new FieldList());
            var tempItem = new Item(ID.NewID, itemData, this.renderingContext.ContextItem.Database);

            var parametersCollection = WebUtil.ParseUrlParameters(this.renderingContext.Rendering["parameters"]);

            TTemplate item;

            using (new SecurityDisabler()) 
            {
                using (new EnforceVersionPresenceDisabler())
                {
                    tempItem.Editing.BeginEdit();
                    var fields = parametersCollection.AllKeys;
                    foreach (var fieldName in fields.Where(fieldName => tempItem[fieldName] != null))
                    {
                        tempItem[fieldName] = parametersCollection[fieldName];
                    }

                    tempItem.Editing.EndEdit();
                    item = tempItem.As<TTemplate>();
                }
            }

            return item;
        }

In the method signature I have also used IStandardRenderingParametersItem instead of IStandardTemplateItemwhich is I think is more restrictive, secure and semantic.

Also I think it will work really nice with another proposed enchancement: Include IStandardRenderingParametersItem in Synthesis . Then IStandardRenderingParametersItem type can be supplied from Synthesis assembly - as IStandardTemplateItem already does.