Users register interest in the Chatter activity of a record by clicking Follow icons in the Force.com user interface or by automatically following owned records. Users can follow other users as well as records in standard and custom objects. The information about followers is prominently displayed throughout the standard user interface, and used to email digests and notifications to users if Chatter is configured to do so.
All of this functionality hinges upon a single, simple object, called EntitySubscription
. Its two important fields are ParentId
, the record being followed, and SubscriberId
, the Id of the user doing the following. For every record-to-user relationship in the organization, a unique record in EntitySubscription
exists to express it.
With simple queries on the EntitySubscription
object, you can retrieve a list of records followed by a user, or the users following a specific record. Less useful might be a query for the full set of following relationships in the entire organization, as shown in Listing 12.10.
SELECT ParentId, SubscriberId, CreatedById, CreatedDate
FROM EntitySubscription
To follow a record programmatically, insert a new ParentId
and SubscriberId
pair into the EntitySubscription
object. Listing 12.11 provides a sample method to do this. Test it by passing in the Id of a record to follow and the Id of a User record to follow it.
public Id follow(Id recordId, Id userId) {
EntitySubscription e = new EntitySubscription(
ParentId = recordId, SubscriberId = userId);
insert e;
return e.Id;
}
For example, call it with the Id of an Account record and your user’s Id value; then refresh the Account’s view page to see yourself instantly listed as a follower. Make a note of the Id value returned by the method. This is used later to unfollow the record.
Note
Each EntitySubscription record uniquely identifies a relationship between parent record and User record, so a runtime error is thrown if a new record matches an existing record’s ParentId
and SubscriberId
.
Unfollowing a record involves deleting the appropriate row in the EntitySubscription
object that relates the record to the user. Listing 12.12 provides a sample method for doing just that. To use the method, pass the EntitySubscription record identifier returned by the follow
sample method in Listing 12.11.
public void unfollow(Id subscriptionId) {
delete [ SELECT Id FROM EntitySubscription
WHERE Id = :subscriptionId ];
}
Although this simple example can work, it’s unlikely that your program would possess the unique identifier of the EntitySubscription record. You could just as easily delete records on more readily available information, such as the EntitySubscription’s ParentId
or SubscriberId
.
18.117.190.170