The Site Doctor Blog

Footprints in the snow of a warped mind

< Back to Blog

Power Ucommerce facet display names from the CMS

The index changes released in v9 have been great and API is blazingly fast -however it's come with a couple of costs when it comes to configuring the Facet settings via the UI.

Setting the DisplayName for the facet within code as per the documentation feels like a big step backwards. Don't worry though, you can work around it with this simple Extension method.

Add the FieldDefinitionExtensions class below to your project and then you can automatically add any descriptions like this:

this.Field(p => p["YourPropertyName"], typeof(string)).DisplayNameFromUcommerce().Facet();

Hope that helps someone else!

using System.Collections.Generic; using System.Linq; using Ucommerce.EntitiesV2; using Ucommerce.Search;

namespace TSD.Core.Commerce.Common.Extensions
{
    public static class FieldDefinitionExtensions
    {
        private static readonly IRepository<ProductDefinitionField> ProductDefinitionFieldRepository = Ucommerce.Infrastructure.ObjectFactory.Instance.Resolve<Ucommerce.EntitiesV2.IRepository<Ucommerce.EntitiesV2.ProductDefinitionField>>();
        private static Dictionary<string, ICollection<ProductDefinitionFieldDescription>> AllDisplayNames;

        public static FieldDefinition<T> DisplayNameFromUcommerce<T>(this FieldDefinition<T> self)
        {
            var displayName = GetProductDefinitionFieldDescriptions(self.Name);
            foreach (var description in displayName)
                self.DisplayNames[description.CultureCode] = description.DisplayName;
            return self;
        }


        private static void EnsureProductDefinitionFields()
        {
            if (AllDisplayNames != null) return;

            AllDisplayNames = new Dictionary<string, ICollection<ProductDefinitionFieldDescription>>();

            var definitionFields = ProductDefinitionFieldRepository.Select(f => f.Deleted == false);

            foreach (var field in definitionFields)
            {
                if (!AllDisplayNames.ContainsKey(field.Name))
                    AllDisplayNames.Add(field.Name, field.ProductDefinitionFieldDescriptions);
            }
        }
        private static ICollection<ProductDefinitionFieldDescription> GetProductDefinitionFieldDescriptions(string key)
        {
            EnsureProductDefinitionFields();

            return (AllDisplayNames.TryGetValue(key, out var descriptions)) ? descriptions : Enumerable.Empty<ProductDefinitionFieldDescription>().ToList();
        }
    }
}
Author: Tim on

Liked this post? Got a suggestion? Leave a comment