October 27, 2016 Development Tips

Kentico Custom Macro Method To Get Column Names

By: Laura Frese
In this post I provide a quick code snippet to create a custom macro that will allow you to pull all of the column / field names for a specified Kentico class. This macro comes in handy when you want to quickly specify which columns to pull in using the repeater web part. In addition, the macro accepts an additional parameter so that you can indicate which columns to omit. In my next post, I will use this as an example of how to cache data using the Kentico API.

If you arent familiar with the famous Kentico CMS macros, you can learn more about them in the documentation
First, start out by creating a custom macro. If you are not familiar with creating custom macros, take a peek at the documentation provided by Kentico.  
Add the following method to your file: 

    [MacroMethod(typeof(string), "Gets all of the column names associated with a table", 1)]
    [MacroMethodParam(0, "ClassName", typeof(string), "Name of the class")]
    [MacroMethodParam(1, "OmitFields", typeof(string), "Names of the fields to omit, sepearted by comma")]
    public static object GetClassColumns(EvaluationContext context, params object[] parameters)
        string classname = ValidationHelper.GetString(parameters[0], "").Trim().ToLower();
        string omit = "";
        if (parameters.Length > 1)
            omit = ValidationHelper.GetString(parameters[1], "").ToLower();
        if (classname != "")       
            DataClassInfo classInfo = DataClassInfoProvider.GetDataClassInfo(classname);
            if(classInfo != null)
                List<string> columns_list = new FormInfo(classInfo.ClassFormDefinition).GetColumnNames();
                columns_list = columns_list.ConvertAll(d => d.ToLower());
                if (omit != "")
                    foreach (string s in omit.Split(','))
               columns = columns_list.Join(",");
              return columns;

You can download the full code here.

Once you have registered the custom macro method, you will see it appear in any macro code editor in the CMS. To test the macro, go to System > Macros > Console and enter the expression
"CMS.Blog".GetClassColumns("BlogTeaser, BlogID") 
This will return all columns associated with the Blog class except for the BlogTeaser and BlogID.
Test Custom Macro Method