function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jack Rose 1Jack Rose 1 

Apex class to add Data Categories to an Article field

Hi All, 

Looking for some help, I'm an Admin with no access to a developer. I am looking at creating an Apex Class to insert the data categories into a fields on knowledge articles. I have found the below details on how to achieve this. I'm unsure how I am able to do this with mapping a particular category group to a particular field, any suggestions?



In Salesforce, open the Developer Console (see Open the Developer Console).
Create a new Apex Class.
For this tutorial, you can name your class DataCategoryMgmt.
In your Apex Class, enter the following template:


public class DataCategoryMgmt {
  @InvocableMethod
    public static void updateArticleTypeForDataCategories(List<Id> articleTypeIds)
    {
        List<Knowledge__kav> lstArticleType = [SELECT Id, Title, Data_Categories__c FROM Knowledge__kav WHERE Id IN:articleTypeIds
                                                    AND PublishStatus = 'draft'];
 
        List<Knowledge__DataCategorySelection> lstDC = [SELECT ParentId, DataCategoryName   FROM Knowledge__DataCategorySelection
                                                            WHERE ParentId IN:articleTypeIds];
 
        Map<Id, String> datacategoryNameMap = new Map<Id, String>();
 
        for(Knowledge__DataCategorySelection dcObj:lstDC)
        {  
            if(datacategoryNameMap.containsKey(dcObj.ParentId))
            {
                String str =  datacategoryNameMap.get(dcObj.ParentId);
                datacategoryNameMap.put(dcObj.ParentId, str + ';' + dcObj.DataCategoryName);
            }
            else
            {
                datacategoryNameMap.put(dcObj.ParentId, dcObj.DataCategoryName);
            }
        }
 
        for(Knowledge__kav artObj:lstArticleType)
        {
            if(datacategoryNameMap.containsKey(artObj.Id))
            {
                artObj.Data_Categories__c = datacategoryNameMap.get(artObj.Id);
            }
        }
 
        update lstArticleType;
    }   
}


Adapt the template to your use case:
Change all six instances of Knowledge to the name of the article type you wish to modify.
Change both instances of Data_Categories__c to the API name of the field you have just created.
If you changed the name of your Apex class, remember to change DataCategoryMgmt to your new Apex class name.
Save your Apex Class.