Synthesis icon indicating copy to clipboard operation
Synthesis copied to clipboard

Add Synthesis Rendering Parameters Helper

Open blipson89 opened this issue 5 years ago • 1 comments

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

blipson89 avatar Apr 23 '19 16:04 blipson89

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 IStandardTemplateItem which 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.

kukens avatar May 01 '19 07:05 kukens