API Questions on Kentico API.
Version 6.x > API > Add a Category to a Document View modes: 
User avatar
Member
Member
scott_hancock-urmc.rochester - 6/13/2012 3:47:49 PM
   
Add a Category to a Document
Hi,

I'm writing a Custom Event that will automatically add a category to a document when it is created. My problem is that I cannot figure out how to add a category to a document. Here is what I have:

public partial class CMSModuleLoader
{
/// <summary>
/// Attribute class that ensures the loading of custom handlers
/// </summary>
private class CustomDocumentEventsAttribute : CMSLoaderAttribute
{
/// <summary>
/// Called automatically when the application starts
/// </summary>
public override void Init()
{
// Assigns custom handlers to the appropriate events
DocumentEvents.Insert.After += Document_Insert_After;
DocumentEvents.InsertLink.Before += Document_InsertLink_Before;
}

private void Document_Insert_After(object sender, DocumentEventArgs e)
{
// Add custom actions here
if (e.Node.DocumentNamePath.StartsWith("/Test"))
{
e.Node.Categories.Add(CategoryInfoProvider.GetCategoryInfo("Hospital", CMSContext.CurrentSiteName));

}
}

private void Document_InsertLink_Before(object sender, DocumentEventArgs e)
{
// Add custom actions here
}
}
}


I don't get an error, the code runs fine but no category is added to the document. What am I missing?

Thanks,
Scott

User avatar
Kentico Support
Kentico Support
kentico_janh - 6/14/2012 3:34:33 AM
   
RE:Add a Category to a Document
Hello,

The right code for adding a category to a document is the following one:

CMS.SiteProvider.CategoryInfo ci = CMS.SiteProvider.CategoryInfoProvider.GetCategoryInfo("Web", CMSContext.CurrentSiteName);
CMS.TreeEngine.DocumentCategoryInfo dci = new CMS.TreeEngine.DocumentCategoryInfo();
dci.CategoryID = ci.CategoryID;
dci.DocumentID = e.Node.DocumentID;
dci.Update();

Best regards,
Jan Hermann