How to get a text value instead of an ID from a list field

This article gives you instructions on how to implement a transformation function to get a text value instead of an ID, if your field is defined as a list of pair values (e.g. Drop-down list).
As you probably know, Kentico stores the ID value of your field if it is defined as a list (1;Red | 2;Green | 3;Blue) not the SQL query (in that case you would need to get those text values from the database). However you can easily get its text value if you implement the transformation function below. Please follow this link to our documentation where it's described, how to implement custom transformation functions.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using CMS.FormEngine; using CMS.GlobalHelper; using CMS.SettingsProvider; using System.Collections; namespace CMS.Controls { /// <summary> /// Extends the CMSTransformation partial class. /// </summary> public partial class CMSTransformation { public static string MyGetValue(object fieldName, object nodeClassId, object id) { DataClassInfo classInfo = DataClassInfoProvider.GetDataClass(ValidationHelper.GetInteger(nodeClassId, 0)); if (classInfo != null) { FormInfo formInfo = new FormInfo(classInfo.ClassFormDefinition); FormFieldInfo ffi = formInfo.GetFormField(ValidationHelper.GetString(fieldName, "")); if (ffi != null) { List<string> optionsList = ffi.Settings["Options"].ToString().Split('\n').ToList(); optionsList = optionsList.Select(s => s = s.Trim()).ToList(); Hashtable options = new Hashtable(); optionsList.ForEach(s => options.Add(s.Split(';')[0], s.Split(';')[1])); if (options[id] != null) { return options[id].ToString(); } } } return ""; } } }

< % # MyGetValue("ListValue", Eval("NodeClassID"), Eval("ListValue"))  % >

Where ListValue is a column name of given list field.

If you want you can take advantage of our caching feature and extend this example to let data to be queried only once ->

You can use the same code or call this already implemented function in custom macro method ->

See also:

Applies to: Kentico 7.x
Share this article on   LinkedIn