Kentico CMS 6.0 Developer's Guide

Adding custom functions to transformations

Adding custom functions to transformations

Previous topic Next topic Mail us feedback on this topic!  

Adding custom functions to transformations

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

In many cases, you may need to process values and display them in a different format or add custom conditions. The following example shows you how to create a custom function that will return the first N characters of a text and how to use it in a transformation.

 

Open the 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 call it as your site code name. Right-click the folder and choose Add New Item. Choose to add a new Class and call it MyFunctions.cs (custom transformation functions can be developed only in C# at this moment).

 

devguide_clip0152

 

Paste the following code to the MyFunctions.cs file:

 

[C#]

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

/// <summary>

/// Summary description for MyFunctions

/// </summary>

public static class MyFunctions

{        

        public static string TrimText(object txtValue, int leftChars)

        {

            if (txtValue == null | txtValue == DBNull.Value)

            {

                return "";

            }

            else

            {

                string txt = (string) txtValue;

                if (txt.Length <= leftChars)

                {

                    return txt;

                }

                else

                {

                    return txt.Substring(0, leftChars) + "...";

                }

            }

        }   

}

 

Please note: The function must be defined as static so that you can call it from the transformation.

 

Then, go to Site Manager -> Development -> Document types and Edit (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:

 

 

..
 
<p><%# MyFunctions.TrimText(Eval("NewsSummary"), 20) %><br /><br />
 
..

 

Click Save to confirm the modification. Go to the live site and view the News page. As you can see, the news summary text is truncated to the first 20 characters.

 

In this topic, you have learned how to write your own transformation 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.