Sitecore Custom Item Resolver Pipeline

Sitecore with SXA is really easy and simple to work with redirects. When you have a product, ring as example, it has multiples carat weight so you create 3 variants.

You can use as base template SXA redirect item /sitecore/templates/Feature/Experience Accelerator/Redirects/Redirect with that you can see on screen Redirect Url section:

We can define on “Nicky Ring” product the redirect URL to Carat weight 070. It will work good. But we have a different scenario, I need to redirect to this product when I type on Url http://mysite.com/products?ref=REF12354 as “ref” my Reference number on Sitecore product item.

How can I do that? Don’t worry we will take over bellow.

First you need to create a Custom Pipeline on your config file in Visual Studio Solution:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <httpRequestBegin>
        <processor patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']" type="MyProject.Foundation.SitecoreExtensions.ItemResolver.ItemResolver, MyProject.Foundation.SitecoreExtensions" />
      </httpRequestBegin>
    </pipelines>
  </sitecore>
</configuration>

After that you create your class:

public class ItemResolver : HttpRequestProcessor
{
        public override void Process(HttpRequestArgs args)
        {
        }
}

When you have your class so now it’s the most fun part that I love.. Implement our code.

On this example, I’m getting url, verifying my parameter “ref=”.

If exits, I will do my Sitecore Query to get this item. After that we have to check if item is not null to get item url, otherwise we redirect to site homepage.

var url = HttpContext.Current.Request.Url.AbsoluteUri;
            if (url.Contains("ref="))
            {
                var myUri = new Uri(url);
                try
                {
                    var refParam = HttpUtility.ParseQueryString(myUri.Query).Get("ref");
                    var sitecoreUrlItem = SitecoreUrlItem(refParam);
                    if (!string.IsNullOrEmpty(sitecoreUrlItem))
                        args.HttpContext.Response.RedirectPermanent(sitecoreUrlItem);
                }
                catch (Exception)
                {

                }
            }
private string SitecoreUrlItem(string refNumber)
        {
            var url = string.Empty;
            try
            {
                var sitecoreDB = Sitecore.Context.Database;
                var sitecoreQuery = $"/sitecore/content/MySite/Home/Products//*[@ReferenceNumber ='{refNumber}']";
                var prodItem = sitecoreDB.SelectSingleItem(sitecoreQuery);
                if(prodItem != null)
                {
                    url = LinkManager.GetItemUrl(prodItem);
                }
                else
                {
                    var homeItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);
                    url = LinkManager.GetItemUrl(homeItem);
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error($"Error to Redirect to product with ReferenceNumber:{refNumber}", ex.Message);
            }
            return url;
        }

It’s done! With that you have your custom Redirect url to specific item.

If you have any question or any suggestion, leave your comment or send me an email!

Peace!

Custom Validation Message Sitecore Forms

When you are working with Sitecore Forms is a little bit trick to work with multiple languages. It’s easy to manage simple stuffs like: Label names, datasources, field type, form structure, submit actions, etc.. But when you start to go deep as example Validation Message in other languages, it’s trick.

First you are able to translate a Sitecore default messages on /sitecore/system/Settings/Forms/Validations. For example String Length Validator:

when {0}=field name {1}=minimum characters {2}=max characters

You can include a new version for language and change the message Text as example in Japanese bellow:

Those examples above is for sitecore default messages, but we have another scenario when the client needs more custom, I mean, in some languages the order of text changes. for example in english you have “{field name} is required” in french you have “Veuillez indiquer votre {field name}.” so for this case you need to create a custom Validation Message.

First you need to create your sitecore Validation Item in /sitecore/system/Settings/Forms/Validations folder you insert a new item from template /sitecore/templates/System/Forms/Validation. Once you created the item it shows settings on content tab:

Type: you need to Put your .Net class path as example: ProjectName.Foundation.Forms.Validators.RequiredFields.RequiredFieldsCustomValidation,ProjectName.Foundation.Forms.

Message: the message that you want to display as example: “First Name is required.”

I created on my Visual Studio solution a generic glass for required fields to display the message. See this class bellow:

public class RequiredFieldsCustomValidation : ValidationElement<string>
    {
        public RequiredFieldsCustomValidation(ValidationDataModel validationItem) : base(validationItem)
        {
        }

        public override IEnumerable<ModelClientValidationRule> ClientValidationRules
        {
            get
            {
                var clientValidationRule = new ModelClientValidationRule
                {
                    ErrorMessage = FormatMessage(Title),
                    ValidationType = "required"
                };

                yield return clientValidationRule;
            }
        }

        public string Title { get; set; }

        
        public override ValidationResult Validate(object value)
        {
            if (value == null)
            {
                return new ValidationResult(FormatMessage(Title));
            }

            var stringValue = (string)value;
            if (string.IsNullOrEmpty(stringValue))
            {
                return new ValidationResult(FormatMessage(Title));
            }

            return ValidationResult.Success;
        }

        public override void Initialize(object validationModel)
        {
            base.Initialize(validationModel);

            var obj = validationModel as StringInputViewModel;
            if (obj != null)
            {
                Title = obj.Title;
            }
        }
    }

Once you create your Item on Sitecore and your class on Visual Studio now its time to update Sitecore Field item on “Allowed Validations Section“. you can check on /sitecore/system/Settings/Forms/Field Types as this example I will include on “Single-line text” (/sitecore/system/Settings/Forms/Field Types/Basic/Single-Line Text) field because its a “First name” Item.

After that you go to Sitecore Forms builder to select your new Validation Message.

You can now update message field on item “/sitecore/system/Settings/Forms/Validations/First Name Validator“for all languages.

As you can see bellow:

English

French:

That’s it guys!

If you have any question, leave your comment or send me an email!

Peace!