Using Apex with Knowledge

 

In continuation of my effort to make Lightning Knowledge easily understandable for all, today I am going to show how Salesforce Knowledge can be accessed using Apex. Salesforce Knowledge can have Apex Triggers and be accessible through Apex code. Actually, Salesforce provides some standard apex classes related to Knowledge Management that can be called for actions like publishing, editing as draft, archiving, and more.

Before I start, I would recommend you going through my earlier posts –

We can use the methods in KbManagement.PublishingService class to manage the lifecycle of an article. I am going to explain some of the few classes which developer needs mostly, but to know about all the methods, I highly recommend you going through the documentation here.

Editing an Article as Draft

We can use the below method to edit an article as draft – 

String newId = KbManagement.PublishingService.editOnlineArticle(
                    knowledgeArticleId,
                    false
               );

Where the 1st input parameter is the KnowledgeArticleId (Note – This is not the Knowledge Record Id).
2nd parameter is a Boolean value where false will not unpublish the already published articles and true will unpublish the already published article.
This method will return the new draft master version ID of the article.
Note – We need to keep this in mind that this method is not bulkified. So if you are trying to bulk edit a lot of published articles, this method will fail as it will throw Salesforce Limit. So the workaround is to implement Queueable class like below, where you call the queueable method with the batch size of your choice.
Queueable Class –

public class KnowledgeEditQueue implements Queueable {
List<Knowledge__kav> allKnowledges = new List<Knowledge__kav>();

public KnowledgeEditQueue(
List<Knowledge__kav> allKnowledges
) {
this. allKnowledges = allKnowledges;
}

public void execute(QueueableContext qc) {
List<String> newVersionIds = new List<String>();
String newVersionId;

for (Knowledge__kav single : allKnowledges) {
newVersionId = KbManagement.PublishingService.editOnlineArticle(
single.KnowledgeArticleId,
false
);
newVersionIds.add(newVersionId);
}
}

}

Calling the Queueable Method –
if (allArticles.size() > 0) {
    Integer count = 0;
List<Knowledge__kav> scope = new List<Knowledge__kav>();

for (Knowledge__kav single : allArticles) {
    if (count < BATCH_SIZE) {
    count++;
scope.add(single);
} else if (count == BATCH_SIZE) {
count = 0;
System.enqueueJob(new KnowledgeEditQueue(scope));
scope = new List<Knowledge__kav>();
scope.add(single);
}
}
if (!scope.isEmpty()) {
    System.enqueueJob(new KnowledgeEditQueue(scope));
}
}

Publish an Article 

We can use the below method to publish an article  – 

KbManagement.PublishingService.publishArticle(
      knowledgeArticleId,
      false
);

Where the 1st input parameter is the KnowledgeArticleId (Note – This is not the Knowledge Record Id).
2nd parameter is a Boolean value where false will not publish the article as a new version, whereas true will publish the article as a new version.
This method is not bulkified, so you can use the same mechanism of Queueable class to bulk publish articles.

Schedule Article Publication

We can use the below method to schedule article publication – 

Datetime scheduledDate = Datetime.newInstanceGmt(2012, 12,1,13,30,0);
KbManagement.PublishingService.scheduleForPublication(
      knowledgeArticleId,
      scheduledDate
);

Where the 1st input parameter is the KnowledgeArticleId (Note – This is not the Knowledge Record Id).
2nd parameter is the schedule date (If nothing is specified, then the article will be published immediately).


Delete Draft Article 

We can use the below method to delete draft article – 

KbManagement.PublishingService.deleteDraftArticle(
      knowledgeArticleId
);

Where the 1st input parameter is the KnowledgeArticleId (Note – This is not the Knowledge Record Id).

Archive Online Article

We can use the below method to archive online article – 

Datetime scheduledDate = Datetime.newInstanceGmt(2012, 12,1,13,30,0);
KbManagement.PublishingService.archiveOnlineArticle(
      knowledgeArticleId,
      scheduledDate
);

Where the 1st input parameter is the KnowledgeArticleId (Note – This is not the Knowledge Record Id).
2nd parameter is the schedule date (If nothing is specified, then the article will be archived immediately).

Trigger Consideration for Knowledge Articles

ActionWhich Trigger Context
New Article SavedBefore Insert and After Insert
Existing Draft Articles Saved AgainBefore Update and After Update
Publish ArticleNo
Archive ArticleNo
Edit as DraftBefore Insert and After Insert
Undelete Article From Recycle BinNo
Delete ArticleBefore Delete and After Delete
AssignBefore Update and After Update (Only when the article is edited before being assigned)
Importing ArticlesBefore Insert and After Insert
Importing Articles with TranslationBefore Update and After Update

I hope this will help you when dealing with Knowledge from Apex. If you have any feedback, please post it in the comment section. Thank you.

Handy SOQL/SOSL Queries for Knowledge

 

Happy Monday!! In my last post, I have explained the Data Model around Salesforce Lightning Knowledge. If you haven’t gone through that post, I highly recommend you going through the post “Understanding Salesforce Lightning Knowledge Data Model“ as it is going to help you to understand the queries in this post.

Let’s first create the article – “Hello World” and below are the different versions with different publishing status. Below article properties which I will be using the query –

  • Article Number: 000001000
  • Knowledge Article Id: kA03t00000063w2CAA

Fetching Latest Knowledge Article Version

SELECT Id,PublishStatus,Title FROM Knowledge__kav WHERE KnowledgeArticleId = 'kA03t00000063w2CAA' AND IsLatestVersion = True

Fetching Published Knowledge Article Version

SELECT Id,PublishStatus,Title FROM Knowledge__kav WHERE KnowledgeArticleId = 'kA03t00000063w2CAA' AND PublishStatus = 'Online'

Fetching Draft Knowledge Article Version

SELECT Id,PublishStatus,Title FROM Knowledge__kav WHERE KnowledgeArticleId = 'kA03t00000063w2CAA' AND PublishStatus = 'Draft'

Fetching Archived Knowledge Article Versions

SELECT Id,PublishStatus,Title FROM Knowledge__kav WHERE KnowledgeArticleId = 'kA03t00000063w2CAA' AND PublishStatus = 'archived' AND IsLatestVersion = False
This one is tricky, as to query Archived article versions, KnowledgeArticleId and IsLatestVersion = False and PublishStatus = archived should be mentioned.

Note –
Using bind variables with Apex SOQL Statements with KnowledgeArticleVersion is not allowed. So you need to use dynamic SOQL like below –
final String ONLINE_ARTICLE = ‘Online’;
final String myQuery = ‘SELECT Id FROM Knowledge__kav WHERE PublishStatus = :ONLINE_ARTICLE’;
List<Knowledge__kav> allArtciles = Database.query(myQuery);

Working with DATA CATEGORY

WITH DATA CATEGORY is an optional clause in SOQL and it helps to identify articles linked with one or more data categories.
You can use WITH DATA CATEGORY to fetch articles FROM ObjectTypeName where 
  • ObjectTypeName = KnowledgeArticleVersion to query all articles types.
  • ObjectTypeName = an article type API Name to query a specific article type.
  • ObjectTypeName = Question to query questions.
Note – When ObjectTypeName = KnowledgeArticleVersion or any article type API Name, then WHERE clause is mandatory. You can put one of the below things in the WHERE clause –
  • PublishStatus 
    • “online” to published articles.
    • “archived” to query archived articles
    • “draft” to query draft articles
  • Id = articles Id.
SOQL Query –

SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY NorthAmerica__c ABOVE canada__c
Note – WITH DATA CATEGORY, only AND logical operator is allowed. 

DATA CATEGORY Filtering Selectors

Let’s say we have the below data category structure –

Earth__c
Asia__c
India__c
Bangladesh__c
NorthAmerica__c
Canada__c
USA__c
Europe__c
Switzerland__c
France__c
German__c
Example 1: Fetch all published articles from Canada 

SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY Earth__c AT Canada__c
Example 2: Fetch all published articles above German

SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY Earth__c ABOVE German__c
This will fetch articles linked with German, Europe, Earth data categories.
Example 3: Fetch all published articles below Asia

SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY Earth__c BELOW Asia__c
This will fetch articles linked with Asia, India, Bangladesh data categories.
Example 3: Fetch all published articles above or below Europe

SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY Earth__c ABOVE_OR_BELOW Europe__c
This will fetch articles linked with Europe, Switzerland, France, German, Earth data categories.
To know more about, please read this great section here.
Thank you and please let me know if you have any handy queries in the comment section.

Understand Salesforce Lightning Knowledge Data Model

While working with Lightning Knowledge, what I realized is that there is hardly any tutorial/post which explains the Knowledge Data Model in a very simple way. So I thought of writing my understanding with examples covering the part of the data model. I hope this will help you to understand the data model clearly and quickly.

Understanding the data model is always very important while doing the development as it will help you to play with the objects and do configure/customization that is possible, basically getting the maximum benefit of the platform.
To start with, the Knowledge Object Model is based on Abstract and Concrete objects. 

Core Abstract and Concrete Objects

The core abstract objects are – KnowledgeArticle and KnowledgeArticleVersion. The corresponding concrete versions are – Knowledge__ka and Knowledge__kav.
Below is the data model from the Salesforce Developer Guide –

Complete Data Model 

Relationship between Knowledge__ka and Knowledge__kav

As per the data model, the relationship between Knowledge__ka and Knowledge__kav is 1 to many. That is one Knowlegde__ka can have multiple Knowledge__kav. The link is happening through KnowledgeArticleId (remember KnowledgeArtcileId and Id are two different fields). So let’s check the example below.
The “HelloWorld” article is having two versions – 

Now if I run the query against Knowledge__ka, I am getting one entry which provides me the KnowledgeArticleId

Now with the same KnowledgeArticleId, if I query Knowledge__kav, I will get one entry. Surprised?? Why only one entry where it should be two. The reason is that when you publish version 2, version 1 is marked as Archived. So SOQL query will not count the archived versions.

If I create another version and mark that as Draft (not publish), then the query will return two entries like below –

Note – Here is the link –

Knowledge__ka.Id = Knowledge__kav.KnowledgeArticleId

Relationship between Knowledge__kav and Knowledge__DataCategorySelection

Here is the same above document with two DataCategory – India and Canada

Note – Here is the link –

Knowledge__kav.Id = Knowledge__DataCategorySelection.ParentId

Relationship between Knowledge__ka and Knowledge__ViewStat

Knowledge__ViewStat is derived from abstract object KnowledgeArticleViewStat. It is used to store the number of views for a specific article.
The link is –

Knowledge__ka.Id = Knowledge__ViewStat.ParentId

Here is the query 

Relationship between Knowledge__ka and Vote

The object is used to store information about Upvote and Downvote against the article.
The link is –

Knowledge__ka.Id = Vote.ParentId

Here is the query 

I hope this will help you to understand the data model. Please let me know your feedbacks. Thanks.

Queueable Apex

 

Earlier I wrote a blog post dedicated to Asynchronous processing in Salesforce. This time I will focus on Queueable Apex only.

Queueable Apex is a more advanced version of future methods. It has all the functionalities of the future method along with the power of Batch Apex. So – 

Queueable Apex = Future Method + Batch Apex

It provides additional job chaining and allows for more complex data types.
With Queueable Apex, developers will be able to submit jobs for asynchronous processing, like something future method can do as well. But the difference comes here –
  • Flexibility in method parameters: With Queueable Apex, developers will be able to create classes that will allow member variables of non-primitive data types like sObjects or custom Apex types. 
  • Monitor the progress: Once the developer submits a job by executing the command System.enqueuJob, it provides an ID, which is basically a Job Id. With that Id, the developer can now query the progress either from Salesforce interface in the Apex Job page or by querying the AsyncApexJob table.
  • Chaining jobs: Developer can now chain jobs i.e. starting a new queueable job from an already running queueable job.

Batchable vs Future vs Queueable

Batchable was the first one introduced by Salesforce for asynchronous heavy processing. It was “heavy” in terms of resource usage and also needs longer time to process/complete the work.
To solve the problem with Batchable, Salesforce introduced the Future method. It is lighter on resource and can do all the work which were previously done by Batchable jobs but in a much more efficient way. But the problem with the Future is that it will not return any Job Id, so as a developer, you have no option to figure it out whether the future job is completed or not. At the same time, it has only a limited amount of space to store the data,  that is why Future methods only accept Primitive and collections.
To solve the above drawbacks, Salesforce introduced the third version of asynchronous processing i.e. Queueable Apex. It is lighter than Batchable but gives the Job ID, which can be used to know the progress of the job. It also allows developers to pass non-primitive data types. Basically, Queueable is a hybrid solution between the limited future methods and the resource-heavy Batchable interface.

Important points to remember

  • The execution of a queued job counts once against the shared limit for asynchronous Apex method executions.
  • You can add up to 50 jobs to the queue in a single transaction.
  • With chaining, you can start only one job from an already running job. That means there can be only one child job for a parent job. Staring multiple jobs from an already running job is not possible.
  • There is no depth limit in terms of how deep you can chain jobs. That means you can start a child job from parent one, and then start another job from child one and continue the process unlimited number of times. For developer and trial org, the maximum stack depth for chained job is 5.

Queueable Apex

public class AccountQueueableExample implements Queueable {
public List<Account> accList;
public AccountQueueableExample(List<Account> accList) {
this.accList = accList;
}
public void execute(QueueableContext context) {
for (Account acc : accList) {
// Update the Account Name
acc.Name = acc.Name + ‘Technical Potpourri’;
}
update accList;
}
}


Call Queueable Apex

List<Account> accList = [SELECT Id, Name FROM Account];
ID jobID = System.enqueueJob(new AccountQueueableExample(accList));


Developer Guide

New Admin Features From Winter 21 Release

In today’s post, I am going to share some of my favorite Admin features from Winter 21 release.

Survey

While creating the survey, admins now have the option of saving the survey as a template. After creating the template, users can open it and make a copy from the top-right menu to create their own survey based on the template.

Flow Enhancements

I have written a separate post covering only flow enhancements coming with Winter 21 release.
Here is the post – Winter 21 Flow Enhancements

Dynamic Form    

With this release, admins now have the power to select the position of the fields in the page layout. As of today, this is only available to custom objects and Lightning App Builder.

When admins will open the record details section from the Lightning page in App Builder, they will be presented with the option to Upgrade (as shown below). Selecting the upgrade option will provide the admins the option to create dynamic forms by positioning fields in different sections on the layout.


Even admins can click on the “Analyze” button at the top right section which will provide them the option whether the customization is good from a performance standpoint.


No More Ref IDs in Email-to-Case

Ref IDs are not always our good friend when dealing with Email-to-Case, as people tend to delete, modify those ugly looking ids when sending emails/replies and that always causes problems with case routing.
The good news is that Ref IDs are going to be phased out. Exact dates will. be announced soon, as there will be an upgrade path to ensure existing Email-to-Case functionalities will still work. After this new features, emails will be matched by information in the email header instead.
As this new feature is coming, I think it is a great time to look out for any automation that exists today in your org which depends on these Ref IDs.

Guest User Access in Communities

Guests users in your communities will be restricted in some of their permissions. This applies to any standard or custom objects with the below permissions –
  • View All Data
  • Modify All Data
  • Edit
  • Delete
If in your community implementation today, you are allowing your guest users to edit existing data, then this is the time when you should consider converting them to community users.

Improved Email Template Creation

Now admins can create email templates by drag and drop functionality. This drag and drop template builder is similar to the page builder and definitely provides a great enhancement to the way we all create email templates today.
Admins can create email templates by going to the “Email Templates” tab and clicking on the New button.

Please let me know your favorite admin features. Enjoy Winter 21 release.