Tuesday 1 June 2021

Sitecore - Create first item version in default language

Recently, we had a request from client wherein they asked us to force the content authors to create items in English version first, if the item doesn't have one. In short, content authors should create item in English version first, than create versions in different languages.

The issue was, accidentally content authors were creating items in different language versions rather than the default English language which is the Fallback language. This was happening mainly on the Media Items where they were creating Media Items like images,PDFs in non-English language due to which they were facing content related issues where image was displaying on X language version page but not on Y language version page.

To Solve the issue, we decided to create a custom validator.

Validator checks the newly created item whether it has the default language version (i.e en).

If Yes, allow content authors to create the language version.

If No, show the validation message.


    [Serializable]
    public class CreateDefaultItemVersion : StandardValidator
    {
        public CreateDefaultItemVersion() { }

        public CreateDefaultItemVersion(SerializationInfo info, StreamingContext context) : base(info, context) { }

        protected override ValidatorResult Evaluate()
        {
            Item item = this.GetItem();
            if (item == null)
            {
                return ValidatorResult.Valid;
            }
            string name = item.Name;

            if (item.Language.Name.Equals("en"))
            {
                return ValidatorResult.Valid;
            }
            else
            {
                Language language = Language.Parse("en");
                var currentItem = Factory.GetDatabase("master").GetItem(item.Paths.FullPath, language);
                if (currentItem?.Versions?.Count > 0)
                {
                    return ValidatorResult.Valid;
                }
                else
                {
                    base.Text = this.GetText(Translate.Text($"The item name `{name}` doesn't have a default English Langauge version. Please create English Version first."));
                    return base.GetFailedResult(ValidatorResult.CriticalError);
                }
            }
        }

        protected override ValidatorResult GetMaxValidatorResult()
        {
            return this.GetFailedResult(ValidatorResult.Error);
        }

        public override string Name => "Always Create Items in English Version First";
    }

 

Once the code is added to the solution, 

Create a validator item under the path /sitecore/system/Settings/Validation Rules. Provide the custom validator class name and the assembly of the class we created and apply the Validation rule.

That's it !!!