How to get all Data Categories using Apex in Salesforce?

How to get all Data Categories using Apex in Salesforce?

Execute the following sample apex code to get all the Salesforce Data Categories using Apex.

Sample Code:

private List < DataCategory > getAllCategories(
    List < DataCategory > categories
) {

    if ( categories.isEmpty() ) {

        return new List < DataCategory >();

    } else {

        List < DataCategory > categoriesClone = categories.clone();
        DataCategory category = categoriesClone[ 0 ];
        List < DataCategory > allCategories = new List < DataCategory > { 
            category 
        };
        categoriesClone.remove( 0 );
        categoriesClone.addAll(
            category.getChildCategories()
        );
        allCategories.addAll(
            getAllCategories(
                categoriesClone
            )
        );
        return allCategories;

    }

}

List < DescribeDataCategoryGroupResult >  describeCategoryResult;
List < DescribeDataCategoryGroupStructureResult > describeCategoryStructureResult;
List < String > objTypes = new List < String >() ;
objTypes.add ( 
    'KnowledgeArticleVersion' 
);
List < DataCategoryGroupSobjectTypePair> typePairs = 
    new List < DataCategoryGroupSobjectTypePair >();
describeCategoryResult = Schema.describeDataCategoryGroups( 
    objTypes 
);

for ( DescribeDataCategoryGroupResult groupResult : describeCategoryResult )  {
    
    DataCategoryGroupSobjectTypePair typePair =
        new DataCategoryGroupSobjectTypePair();
    typePair.setSobject( groupResult.getSobject());
    typePair.setDataCategoryGroupName(
        groupResult.getName()
    );
    typePairs.add( 
        typePair 
    );
    
}

describeCategoryStructureResult = 
    Schema.describeDataCategoryGroupStructures(
        typePairs, false
    );

for ( 
    DescribeDataCategoryGroupStructureResult structRes : 
    describeCategoryStructureResult 
) {
    System.debug(
        'Structure Result Name is ' + 
        structRes.getName()
    );
    
    DataCategory [] toplevelCategories = 
        structRes.getTopCategories();

    List < DataCategory > allCategories = 
               getAllCategories( toplevelCategories );
    
    for ( DataCategory objDC : allCategories ) {
        
        DataCategory [] childCategories = 
            objDC.getChildCategories();
        
        for ( DataCategory objCC : childCategories ) {

            System.debug(
                'Name is ' + 
                objCC.getName()
            );

        }
        
    }
    
}

Leave a Reply