Quick Tip: Retrieving fields for any class in Kentico

   —   

Have you ever needed to get all the fields for a page type in Kentico? Maybe you needed to know the list of fields that make up a class in a custom module. In this blog, I’ll show you a quick way to retrieve the fields for any class in your system.  And just for fun, I’ll implement it using a custom macro.

As with most things in Kentico, it’s quite easy to use the API to get data if you know where to look. Because everything is related within the system, you can quickly access any field (or fields) by specifying the code name for the object. This technique can help you return fields for objects, or even settings and configurations.

If you need to return the list of fields for a page type, the ClassStructureInfo API is your friend. This namespace within the DataEngine API provides access to class-level information for everything in the system. Let me know show you can use this API to get your class fields.

Create a custom macro

To begin, I created a custom macro. For my macro, I chose to have a single parameter passed in, which would be the codename for the class. Next, I added the ClassStructureInfo API call to retrieve list of the columns for the class.

Here is the full macro code.

[MacroMethod(typeof(List<string>), "Returns a list of fields for the class.", 1)] [MacroMethodParam(0, "classcodename", typeof(string), "Class code name.")] public static object GetClassFields(EvaluationContext context, params object[] parameters) { { // Branches according to the number of the method's parameters switch (parameters.Length) { case 1: // Overload with one parameter List<string> lstFields = new List<string>(); lstFields = ClassStructureInfo.GetColumns(ValidationHelper.GetString(parameters[0], "")); return lstFields; default: // No other overloads are supported throw new NotSupportedException(); } } }

With this code, I could easily retrieve a list of columns names for any class.

Testing

In the System / Macros / Console utility, I called the custom macro, specifying various class code names. I started with a page type.

CustomMacroNamespace.GetObjectFields("dancinggoat.article")

Dancing Goat Article

 Next, I chose a system class.

CustomMacroNamespace.GetClassFields("cms.site")

cms.site

With this macro, I could then easily retrieve the information from anywhere in the site. Hopefully, this shows you how easily you can retrieve data using the API. Good luck!

You can learn more about custom macros here.

Share this article on   LinkedIn

Bryan Soltis

Hello. I am a Technical Evangelist here at Kentico and will be helping the technical community by providing guidance and best practices for all areas of the product. I might also do some karaoke. We'll see how the night goes...