Search code examples
tridiontridion-2011

How to get the keyword from category name in C# TBB?


I am trying to fetch the keyword present in the Category using C# TBB to use the output in following DWT TBB.

For that I have a component with the Category field.

I am trying to write the following C# TBB to get the keyword value.

<%@Import NameSpace="Tridion.ContentManager.Templating.Expression" %>        

try
{
    string className = package.GetValue("Component.Fields.title");  
    KeywordField keywordField = package.GetKeywordByTitle(className);

    package.PushItem("Class", package.CreateStringItem(ContentType.Text, keywordField.Value.Key));


}
catch(TemplatingException ex)
{
    log.Debug("Exception is " + ex.Message);
}

But I am getting following compilation error.

Could not compile template because of: error CS0246: The type or namespace name 'KeywordField' could not be found (are you missing a using directive or an assembly reference?) error CS1061: 'Tridion.ContentManager.Templating.Package' does not contain a definition for 'GetKeywordByTitle' and no extension method 'GetKeywordByTitle' accepting a first argument of type 'Tridion.ContentManager.Templating.Package' could be found (are you missing a using directive or an assembly reference?)

Please suggest me how can I achieve it?

Thanks in advance


Solution

  • The error message is absolutely clear what the problem is - there's no reference to the KeywordField class. You need to import the relevant namespace:

    <%@Import NameSpace="Tridion.ContentManager.ContentManagement.Fields" %>
    

    Also absolutely clear is the fact that the Package object doesn't have a method called GetKeywordByTitle. There is a GetByName method, but this is for retrieving a named item from the Package, not for getting an object from the respository.

    Tridion.ContentManager.ContentManagement.Category does have a GetKeywordByTitle method, but to use this you will have to get the category first, which will likely mean having to know the URI of the category.

    Perhaps you need to study the API docs some more?