tridiondd4t

SDL Tridion 2011: Dynamically fill or add a metadata field using a C# TBB


Is it possible to set the value of a metadata field dynamically from a TBB? Or is it possible to dynamically add a metadata field that does not necessarily exist on a schema from a TBB?

The reason I want to do this is that I am using DD4T and I want to have the breadcrumb automatically added into the DD4T xml.

I have tried the following:

    public override void Transform(Engine engine, Package package)
    {
        Initialize(engine,package);

        var page = GetPage();

        string output = page.OrganizationalItem.Title;

        var parent = page.OrganizationalItem as StructureGroup;
        while (parent != null)
        {
            output = GetLinkToStructureGroupIndexPage(parent) + Separator + output;
            parent = parent.OrganizationalItem as StructureGroup;
        }

        // I tried this to dynamically add the field
        //var metadata = page.Metadata.OwnerDocument.CreateElement("breadcrumb");
        //metadata.InnerText = output;
        //page.Metadata.AppendChild(metadata);

        //I tried this to dynamically set an existing field on the schema
        foreach (XmlNode xml in page.Metadata)
        {
            Log.Debug("Metadata field:" +xml.Name);
            if(xml.Name == "breadcrumb")
            {
                xml.InnerText = output;    
            }
        }

        package.PushItem(Package.PageName, package.CreateTridionItem(ContentType.Page, page));
    }

However, neither of these methods seem to work. Is this impossible?


Solution

  • The easiest approach is to create a template class which implements DD4T.Templates.Base.BasePageTemplate. In that class, you implement the method TransformPage, which takes a DD4T page as its argument. You can access the 'TCM page' using the method GetTcmPage().

    Example:

        using TCM = Tridion.ContentManager.CommunicationManagement;
        using Dynamic = DD4T.ContentModel;
    
        public class MyTemplate : BasePageTemplate 
        {
           protected override void TransformPage(Dynamic.Page page)
           {
              TCM.Page tcmPage = GetTcmPage();
              string breadCrumbs = GetBreadCrumbs (tcmPage); // TODO: implement GetBreadCrumbs
              Field f = new Field();
              f.Name = "breadCrumbs";
              f.FieldType = FieldType.Text;
              f.Values.Add(breadCrumbs);
              page.MetadataFields.Add("breadCrumbs", f);
           }
        }