Sitecore has a set “Set Parameters” conditional rendering rule which sets the rendering parameters as the name implies. This rule has some limitations:
- It will remove all existing parameters
- User will have to know the querystring syntax to add the correct keys and values (e.g. parameter1=value1¶meter2=value2)
The second limitation can be resolved by educating the users to use correct syntax, but there is no option to resolve the first one. There are many legitimate scenarios where you would want to set some rendering parameters and either add some more based on a condition or overwrite the value for a particular parameter.
To support this scenario I created a custom conditional rendering rule to do this:
- If there is already a parameter and this is not specified in the conditional rendering rule, then leave it as is.
- If there is already a parameter, and the same is also set in the conditional rendering rule, then overwrite it with the value from conditional rendering rule.
- If the parameter is only in the conditional rendering rule, add it.
I used below code for my custom action:
using Sitecore.Diagnostics; using Sitecore.Rules.Actions; using Sitecore.Rules.ConditionalRenderings; using System.Linq; namespace Jeroen.Rules.ConditionalRendering { public class MergeParameterAction<T> : RuleAction<T> where T : ConditionalRenderingsRuleContext { public string Name { get; set; } public string Value { get; set; } public override void Apply(T ruleContext) { Assert.ArgumentNotNull(ruleContext, "ruleContext"); //grab the existing parameters var parameters = Sitecore.Web.WebUtil.ParseUrlParameters(ruleContext.Reference.Settings.Parameters); //parameter already there, overwrite if (parameters.AllKeys.Contains(Name)) { parameters[Name] = Value; } //add new parameter else { parameters.Add(Name, Value); } //add updated parameters back ruleContext.Reference.Settings.Parameters = string.Join("&", parameters.AllKeys.SelectMany( parameters.GetValues, (n, v) => string.Format("{0}={1}", n, v))); } } }
Below screenshot shows how to add the action:
Now the rule is available in Sitecore and ready to use. You can use the action multiple times in case you need to set multiple parameters as shown here. Now the additional parameters will be set and existing parameters will be kept, there is also no need for the user to remember the syntax, he can just click the name/value pair in the rule editor!