Custom Function

Create and Use Custom Functions

Note: We assume that you have created the data types and added data as described in the demo sample and are going to get Demo.Event items filtered by quarter (Demo.Quarter). Otherwise, customize the code below as you see fit.

In this approach, you need to create a complete function that does the querying and returns the XML you need. It will work similar to the Get<DataType>Xml function and you will be able to use it instead of the standard automatically generated Demo.Event.GetEventXml function.

To create this function:

  1. In the "Function" perspective, select "C# Functions" and click "Add Inline C# Function".
  2. In the window that appears, enter these values:
    • Name: GetEventXmlByQuarter
    • Namespace: Demo
    • Template: Method using data connection
  3. On the "Input Parameters" tab, add the parameter:
    • Name: quarterRef
    • Label: Quarter
    • Type: DataReference<Quarter>
  4. On the "Source" tab, copy and paste this code:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;
    using Composite.Data;
    using Composite.Data.Types;
    
    namespace Demo
    {
    	public static class InlineMethodFunction
    	{
    		public static IEnumerable<XElement> GetEventXmlByQuarter(DataReference<Demo.Quarter> quarterRef)
    		{            
    			using (DataConnection connection = new DataConnection())
    			{
    				return 	from quarter in connection.Get<Demo.Quarter>()
    						join month in connection.Get<Demo.Month>() on quarter.Id equals month.Quarter
    						join anEvent in connection.Get<Demo.Event>() on month.Id equals anEvent.Month		
    						where quarter.Id == (Guid)quarterRef.KeyValue
    						select new XElement("Event", 
    								    new XAttribute( "Id", anEvent.Id ),
    								    new XAttribute( "Name", anEvent.Name ),
    								   		new XElement("Month",
    											    new XAttribute("Name", month.Name)));
    			}           
    		}
    	}
    }
    

    Download the sample code
  5. Save the function.

(As you can see in the code above, XML will be returned for both Event and Month. This is only to demonstrate how you can nest elements with data if you like.)

Now you can use the function in your XSLT. For this:

  1. Edit your XSLT function that should show events filtered by Quarter.
  2. On the "Function Calls" tab, add a function call to Demo.GetEventXmlByQuarter.
  3. For the "Quarter" parameter, you can create and use an input parameter of the Data Reference <Quarter> type
  4. On the "Template" tab, render the XML returned by your Demo.GetEventXmlByQuarter function, for example, by using <xsl:for-each/>.