Adding custom methods to transformations
If you need to add custom logic into your transformations, you can implement custom methods and call them in the transformation code. Custom transformation methods allow you to process field values, display data in custom formats, add conditions, and more.
To create custom methods for ASCX transformations:
- Extend the CMSTransformation partial class in the App_Code folder of your web project.
- Add the definitions of the methods inside the class.
If you wish to add custom functionality for Text transformations, implement custom macro methods.
The following example demonstrates how to create a custom method that trims text values to a specified number of characters.
Writing the custom transformation method
Open your Kentico web project in Visual Studio.
Create a new folder under the App_Code folder (or CMSApp_AppCode -> Old_App_Code if you installed the project as a web application) and name it CustomTransformationMethods.
Right-click the folder and select Add -> Add new Item.
Create a new Class and name it CMSTransformation.cs.
Note: Currently, you must develop transformation methods in C#.
Remove the default content of the class (apart from the basic references) and enter the following code instead:
namespace CMS.Controls { /// <summary> /// Extends the CMSTransformation partial class. /// </summary> public partial class CMSTransformation { /// <summary> /// Trims text values to the specified length. /// </summary> /// <param name="txtValue">Original text to be trimmed</param> /// <param name="leftChars">Number of characters to be returned</param> public string CustomTrimText(object txtValue, int leftChars) { // Checks that text is not null if (txtValue == null | txtValue == DBNull.Value) { return ""; } else { string txt = (string)txtValue; // Returns a substring if the text is longer than specified if (txt.Length <= leftChars) { return txt; } else { return txt.Substring(0, leftChars) + "..."; } } } } }
Save the file. Build the project if it is installed as a web application.
Calling the custom method in ASCX transformations
Log in to the Kentico administration interface.
Open the Document types application.
Edit () the Corporate site - Transformations document type.
Select the Transformations tab.
Edit the BlogsList transformation and change line 5 of its code to the following:
.. <%# CustomTrimText(Eval("BlogDescription"), 50) %> ..
Click Save to confirm the modification.
To check the result, click the Preview button, enter /Community/Blogs into the path textbox on the preview bar and Refresh () the page section. In the preview of the blogs page that uses the transformation (on the sample Corporate site), you can see the text of the blog description truncated to the first 50 characters.