Adding custom functions to transformations

  Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic! 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 custom function that will return first N characters of the text and how to use it in a transformation.

 

Open the web project in Visual Studio. Create a new folder under the App_Code section 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 (the 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 we can easily call it from our transformation.

 

Then, go to Site Manager -> Development -> Document types -> News -> Transformations. Edit the preview transformation and change its code like this:

 

[C#]

 

<b><a href="<%# GetDocumentUrl() %>">

<%# Eval("NewsTitle") %></a></b> (<%# GetDate("NewsReleaseDate") %>)<br/>

<i>

<%# MyFunctions.TrimText(Eval("NewsSummary"), 10) %>

</i>

<br/>

 

Click OK to save. Go to the live site and see the page with news listing. As you can see, the news summary text is truncated to first 10 characters.

 

You have learned how to write your own transformation methods.

Page url: http://devnet.kentico.com/docs/devguide/index.html?adding_custom_functions_to_transformations.htm