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
Scary CowScary Cow 

Auto Follow a record in Communities

It looks like in Communities it's not possible for the communities user to decide if they want to auto follow records they create, so I'm trying to use a trigger to accomplish the same goal.

 

The code I've written (stolen) from other places in the forums works great for internal users.... but for community users creating the same type of record, it throws back an error.

 

I'm pretty sure the problem is the: Userinfo.getUserId()  

Anyone get that working in Chatter Communities yet?

 

Here's the code:

 

trigger AutoFollow on Projects__c (after insert) {

Id aid = [Select Id from Projects__c Order By CreatedDate Desc limit 1].id;
EntitySubscription es = new EntitySubscription();
es.ParentId = aid;
es.SubscriberId = Userinfo.getUserId();
insert es;

}

 

Here's the error:

INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, This person’s information is private because they’re not a member of the community.

Best Answer chosen by Admin (Salesforce Developers) 
alouie_sfdcalouie_sfdc

You might have to set the NetworkId property on the EntitySubscription object, because I think it defaults to the internal network, which your community user doesn't have access to. Can you try adding:

 

es.NetworkId = Network.getNetworkId();

 and see if it fixes the problem?

 

Also, you can avoid a potential race condition in your code by changing this line:

 

Id aid = [Select Id from Projects__c Order By CreatedDate Desc limit 1].id;

to:

 

Id aid = trigger.new[0].Id;

You may also want to bulkify the trigger (iterate over trigger.new) to handle the case where multiple Projects__c objects are inserted at once.

All Answers

alouie_sfdcalouie_sfdc

You might have to set the NetworkId property on the EntitySubscription object, because I think it defaults to the internal network, which your community user doesn't have access to. Can you try adding:

 

es.NetworkId = Network.getNetworkId();

 and see if it fixes the problem?

 

Also, you can avoid a potential race condition in your code by changing this line:

 

Id aid = [Select Id from Projects__c Order By CreatedDate Desc limit 1].id;

to:

 

Id aid = trigger.new[0].Id;

You may also want to bulkify the trigger (iterate over trigger.new) to handle the case where multiple Projects__c objects are inserted at once.

This was selected as the best answer
Scary CowScary Cow

You're a scholar and a gentleman. Worked like a charm. Thank you for your speedy and accurate assistance!

Rongqian ZhangRongqian Zhang
Thank you alouie_sfdc, this is the BEST and ONLY answer on the Internet!