[salseforce][chatter]Chatter Code Recipes

By |10月 20, 2011|chatter, salesforce, |


https://wiki.developerforce.com/index.php/Chatter_Code_Recipes
上記掲載のChatterCodeRecipesを実際に検証しましたので、翻訳と注釈を記載しました。

Recipe 1: Update A User’s Status
ログイン中のユーザが投稿する機能

Visualforce Page
[php]
<apex:inputText value="{!status}" id="status" maxlength="100" />
<apex:commandLink style="button" value="Update User Status" action="{!doUserStatus}" />
[/php]
Custom Controller
[php]
public string status { get; set; }

public PageReference doUserStatus() {
User user = [select id, CurrentStatus from User where id = :UserInfo.getUserId()];
user.CurrentStatus = status;
update user;
return null;
}
[/php]

Recipe 2: Display a User’s Profile Image
ログイン中のユーザのプロフィール画像を表示

Visualforce Page
[php]
<apex:image id="profileImage" url="{!profileImageUrl}" />
[/php]

Custom Controller
[php]
public string profileImageUrl { get; set; }

profileImageUrl = [select FullPhotoUrl from User where Id = ‘1234’];
[/php]

※実際の戻り値は「https://XXXXX.force.com/profilephoto/729U00000004Oz6/F」

Recipe 3: List a User’s Followers
ユーザのフォロワー一覧

Visualforce tags
[php]
<chatter:followers entityId="User Id or record Id"/>
<chatter:feedWithFollowers entityId="User Id or record Id"/>
[/php]

SOQL query
[php]
List<EntitySubscription> followers =
[select id, subscriberid, subscriber.name
from EntitySubscription
where parentid =:uid]; // the id of the user/record for which you want to list followers

Integer noOfFollowers = followers.size();
[/php]

※<chatter:followers entityId=”User Id or record Id”/>と<chatter:feedWithFollowers entityId=”User Id or record Id”/>は同一画面には使用できない。
指定時は下記のようなイメージのみ表示

・<chatter:feedWithFollowers entityId=”User Id or record Id”/>を指定した場合は、ホームタブのChatter部品が表示される
※サンプルのSOQLはフォロワーの人数を算出している。

Recipe 4: List who a User is Following
ユーザのフォロー一覧

SOQL query
[php]
// Everyone you’re following
EntitySubscription[] followingES = [select id, parentid, subscriberid, parent.name
from EntitySubscription
where subscriberid =:uid];//Set to the User’s Id

List<EntitySubscription> following = new List<EntitySubscription> ();
String userSObjectPrefix = User.sObjectType.getDescribe().getKeyPrefix();
for( EntitySubscription es: followingES )
{
if( (” + es.parentid).substring(0,3) ==
userSObjectPrefix) // users only
{
following.add(es);
}
}
Integer followingUserCount = following.size();
[/php]

※上記処理では、ユーザがフォローしているデータを取得後、Userデータのみを抽出している。
抽出方法としてはIDの頭文字3桁で判断する。(実行環境では”005″となっていた)
※フォロワー一覧のように標準部品は用意されていない。

Recipe 5: Follow a User or record
ユーザ・データをフォローする
Visualforce tag
[php]
<chatter:follow entityId="User or Record Id that you want to follow"/>
[/php]

Apex code
[php]
EntitySubscription follow = new EntitySubscription (
parentId = ‘<User Record Id you want to follow’
subscriberid = :UserInfo.getUserId); //your User Id
insert follow;
[/php]

※Visualforce tagでは指定したユーザ/データの状況により、下記どちらかの部品が表示される。

※Apex Codeでは指定したユーザ/データをフォローする旨だが、上記コードではエラーとなる。
正しくは下記。
[php]
EntitySubscription follow = new EntitySubscription ();
follow.parentId = ‘User Record Id you want to follow’;
follow.subscriberid = UserInfo.getUserId(); //your User Id
insert follow;
[/php]

Recipe 6: Add a FeedItem
フィードの投稿
Apex code
[php]
//Adding a Text post
FeedItem post = new FeedItem();
post.ParentId = oId; //eg. Opportunity id, custom object id..
post.Body = ‘Enter post text here’;
insert post;

//Adding a Link post
FeedItem post = new FeedItem();
post.ParentId = oId; //eg. Opportunity id, custom object id..
post.Body = ‘Enter post text here’;
post.LinkUrl = ‘http://www.someurl.com’;
insert post;

//Adding a Content post
FeedItem post = new FeedItem();
post.ParentId = oId; //eg. Opportunity id, custom object id..
post.Body = ‘Enter post text here’;
post.ContentData = base64EncodedFileData;
post.ContentFileName = ‘sample.pdf’;
insert post;
[/php]

※FeedItemクラスについては、APIバージョン21.0以降で使用可能。

Recipe 7: Add a Comment to a FeedItem
フィードに対してコメントを追加する
Apex code
[php]
FeedComment fcomment = new FeedComment();
fcomment.FeedItemId = fId; //Id of the FeedItem on which you want to comment
fcomment.CommentBody = ‘Enter your comment here’;
insert fcomment;
[/php]

Recipe 8: Display my News Feed
自分のNewsFeedを取得
Apex code
[php]
List<NewsFeed> myfeed = [SELECT Id, Type,
CreatedById, CreatedBy.FirstName, CreatedBy.LastName,
ParentId, Parent.Name,
Body, Title, LinkUrl, ContentData, ContentFileName,
(SELECT Id, FieldName, OldValue, NewValue
FROM FeedTrackedChanges ORDER BY Id DESC),
(SELECT Id, CommentBody, CreatedDate,
CreatedBy.FirstName, CreatedBy.LastName
FROM FeedComments ORDER BY CreatedDate LIMIT 10),
(SELECT CreatedBy.FirstName, CreatedBy.LastName
FROM FeedLikes)
FROM NewsFeed
ORDER BY CreatedDate DESC, Id DESC
LIMIT 20];
[/php]
Recipe 9: Display a record’s entity feed
取引先のfeedを取得
Apex code
[php]
List<AccountFeed> myfeed = [SELECT Id, Type,
CreatedById, CreatedBy.FirstName, CreatedBy.LastName,
ParentId, Parent.Name,
Body, Title, LinkUrl, ContentData, ContentFileName,
(SELECT Id, FieldName, OldValue, NewValue
FROM FeedTrackedChanges ORDER BY Id DESC),
(SELECT Id, CommentBody, CreatedDate,
CreatedBy.FirstName, CreatedBy.LastName
FROM FeedComments ORDER BY CreatedDate LIMIT 10),
(SELECT CreatedBy.FirstName, CreatedBy.LastName
FROM FeedLikes)
FROM AccountFeed
WHERE ParentID = ‘<Account Id>’
ORDER BY CreatedDate DESC, Id DESC
LIMIT 20];
[/php]

※商談のFeedの場合は「OpportunityFeed」、カスタムオブジェクトのFeedは「カスタムオブジェクトAPI名__Feed」となる。

Recipe 10: Who has a particular file been shared with
ファイルが共有されたユーザの取得
Apex code
[php]
List<ContentDocumentLink> shares = [SELECT id, LinkedEntityId, ContentDocumentId
FROM ContentDocumentLink
WHERE ContentDocumentId = ‘<File Id>’];
[/php]

※File Idについては必ず指定

Recipe 11: Monitor specific keywords on an entity feed
商談がクローズとなった際、Chatterに出力する直前で処理を行う(トリガ処理)

Apex code
[php]
trigger CheckChatterPostsOnOpportunity on FeedItem (before insert) {
//Get the key prefix for the Opportunity object via a describe call.
String oppKeyPrefix = Opportunity.sObjectType.getDescribe().getKeyPrefix();

for (FeedItem f: trigger.new)
{
String parentId = f.parentId;
//We compare the start of the ‘parentID’ field to the Opportunity key prefix to
//restrict the trigger to act on posts made to the Opportunity object.
if (parentId.startsWith(oppKeyPrefix) &&
f.Body == ‘!close’)
{
//Add business logic here
}
}
}
[/php]

Recipe 12: Monitor user status updates in Chatter
Chatterで誰かが投稿する直前で、任意処理を実施する(トリガ処理)

Apex code
[php]
trigger MonitorUserStatusUpdates on User (before update) {
for (Integer i = 0; i < trigger.new.size(); i++)
{
if (trigger.old[i].CurrentStatus != trigger.new[i].CurrentStatus)
{
//User has changed their Chatter status – take necessary action here.
}
}
}
[/php]

Recipe 13: Integrate Chatter with other social networks OR Migrate Chatter data from one Org to another
ChatterデータをほかのSNSデータと統合するため、データを追加

Apex code
[php]
//Note that this code can only be executed by a user with the ‘Insert System Field Values
//for Chatter Feeds’ permission
FeedItem post = new FeedItem();
post.ParentId = oId; //eg. Opportunity id, custom object id..
post.Body = ‘Enter post text here’;
post.CreatedById = <Salesforce User Id of the original post author>;
post.CreatedDate = <Date and time of original post>;
insert post;

FeedItem f = [select InsertedById from FeedItem where id =:post.Id];
System.assertEquals (f.InsertedById, UserInfo.getUserId());
[/php]