In many cases, you may need to add custom logic into your transformations. This can be achieved by implementing custom methods and calling them in the transformation code. Using this approach, you can process field values, display data in a specific format, add custom conditions etc.
The following example demonstrates how to create a custom method that trims text values to a specified number of characters, and shows how to use it in an ASCX transformation:
1. Open your Kentico CMS web project in Visual Studio. Create a new folder under the App_Code folder (or Old_App_Code if you installed the project as a web application) and name it CustomTransformationMethods.
2. Right click the folder and select Add New Item. Choose to add a new Class called CMSTransformation.cs. Please note that transformation methods must be developed in C# at this time.
3. Remove the default content of the class (apart from the basic references) and enter the following code instead:
As shown above, you can extend the CMSTransformation partial class in the App_Code folder, and then add the definitions of the methods that you wish to call in your transformations.
Save the changes made to the file. Build the project if it is installed as a web application.
4. Now open the Site Manager administration interface, go to Development -> Document types and Edit () the Corporate site - Transformations document type. Select the Transformations tab, edit the NewsList transformation and change line 5 of its code to the following:
Click Save to confirm the modification.
5. To check the result, click the Preview button, enter /News into the path textbox on the toolbar and Refresh () the page section. In the preview of the news page that uses the transformation, you can see the text of the summaries truncated to the first 50 characters:
In this topic, you have learned how to write your own methods for ASCX transformations. If you wish to add custom functionality to a Text transformation, you may implement a custom macro method for this purpose as described in Development -> Macro expressions -> Registering custom macro methods.