Print this page

Inserting FeedItem from a Community User

Knowledge Article Number 000187667
Description Below is simple code, by using which we can insert a FeedItem on any Record, User Chatter Feed
FeedItem post = new FeedItem();
post.ParentId = '005O0000001GXaxxAW'; //Record id/User-id where we want to post feed item
post.Body = 'Find the Today Updates';
insert post;
If we implement a functionality where on a field update above written code which was executing from a trigger. It was working fine for Internal Org users, but same code was giving below exception, if logged-in user is a community User:

System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: 
Resolution Whenever a user from a community is Logged in, and we need to post a FeedItem on behalf of that community user then we need to pass "Current Community Id" in "NetworkScope" field of FeedItem, which tells that  current FeedItem is for which community.

So adding these two line of code resolved issue:
if(Network.getNetworkId() != null){

Here Network.getNetworkId() returns Community Id from which user is logged in. So these two lines will check that if user is logged in from community then we will have to NetworkScope of feedItem.

For more details on Network.getNetworkId check below link:

promote demote