[SalesForce] Posting to Chatter via APEX in a Managed Application – Allow Chatter to be disabled

We are going to enhance our managed package by adding automatic chatter updates when a user takes certain actions in the application.

I found some examples in the Chatter Code Recipes that works nicely:

FeedItem post = new FeedItem();
post.ParentId = MyPostId; // User, Account, Contact or Opportunity 
post.Body = MyPostBody;
insert post;

This works like a charm. The problem that I have is I do not want to force my customers or prospective customers to have chatter enabled in their organization.

If I put the above code into a class in my development org and then I go to Setup – Customize – Chatter – Settings and try to uncheck the 'Enable' to turn on chatter I get a message:

Cannot disable Chatter. It is referenced by the following components: MyApexClassName

Based on more reading I tried the following as supposedly this checks if Chatter is enabled in the org:

if (Schema.SObjectType.User.isFeedEnabled())
{
  FeedItem post = new FeedItem();
  post.ParentId = MyPostId; // User, Account, Contact or Opportunity 
  post.Body = MyPostBody;
  insert post;
}

But still if I try to disable Chatter in the org it gives me the same error message.

Is there a way to write my Apex chatter feed posting such that I don't preclude someone running my Managed Application from turning off chatter ???

Best Answer

You would need to use Reflection so as to not have any compile time reference to chatter entities. So

if (Schema.SObjectType.User.isFeedEnabled())
{
sObject fItem = (sObject)System.Type.forName('FeedItem').newInstance();
fitem.put('ParentId' ,UserInfo.getUserId()); // or Account or Contact or Opportunity Id
fItem.put('Body' ,'Hello world');
insert fItem;
}
Related Topic