Use Name Value List field type, it’s there for a reason

Couple of months ago, I came across a solution that was put in place in Sitecore to have Name – Value pairs or Key – Value pairs for calculation purpose. But the data template’s field names were used as Key and the content editor would enter in the Value. This seemed wrong at that time but I could not think of an apt change to make that solution better and simpler. Recently, while learning about Sitecore fields and field types on my SND course I came across the field type – Name Value List, Straight away I thought, the solution that I had seen a couple of months back could benefit from this field type and could be done a lot better.

The solution that was put into place was just seemed bit odd and have shown it below.

1. A template with a list of fields was created which were the Names, like if one is trying to create a Name – Value or a Key – Value Paired list.

2. The image shows the template created.

Sitecore Data Template

Sitecore Data Template

3. The final template was then inherited from the above template. Showing the inheritance in the below image.

Sitecore Data Template Inheritance

Sitecore Data Template Inheritance

4. The item created from this template was filled out my the content editor. Filled values shown below.

Item created using Template

Item created using Template

By now we get the picture of what is going on and how much maintenance overhead this can be.

Applying the knowledge that I learnt at the SND course, seemed the right way to correct this odd solution. The data template should be modified by changing the field type to Name Value List.

Correct Template

An Item based on this template should be created. Below image shows how the content data should be stored in a Name Value List field type.

Name Value List in Sitecore

Correct way to implement Name Value List in Sitecore

The raw value of Name Value List is stored in a url string format – value_1=20.5&value_2=21.5&value_3=22.5&value_4=23.5&value_5=24.5.

There is no Sitecore web control for this field type.

Lastly the use of Sitecore.Web.WebUtil class comes in handy.

private void FetchNameValueList(Item item)
        { 
            string _urlParamsToParse = item["NameValueListFieldName"];
            NameValueCollection nameValueCollection = Sitecore.Web.WebUtil.ParseUrlParameters(_urlParamsToParse);

            foreach(var nv in nameValueCollection)  
            {
                // Do Stuff
            }
        }

Enumerate through the keys to retrieve the values from the field.

Hope this post gives a better understanding of Name Value List field type and helps implement better and simple solutions.

Thanks to Jason who taught me the recent SND course at Sitecore that inspired me.