0
0

Notes と Notes & Attachments にApexトリガーでレコードを作成する

Last updated at Posted at 2020-11-16

商談の関連でメモ(Notes)とメモ & 添付ファイル(Notes & Attachments)がありますが
商談オブジェクトの説明が更新された時に、その内容をそれぞれにメモに書き込むトリガを考えます。

image.png

メモ & 添付ファイル(Notes & Attachments)の場合

対象のオブジェクトはNoteオブジェクトです。

一括処理に対応できる形でトリガを考えます。

ParentIdには商談のIdをセットすることで参照関係を持たせることができます。

trigger UpdateContentDcomentLink on Opportunity (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
    if (Trigger.isAfter) {
        List<Note> notes = new List<Note>();
        for(Opportunity o : Trigger.new) {
            if((Trigger.isInsert && o.Description!= null) || (Trigger.isUpdate && Trigger.oldMap.get(o.Id).Description != o.Description))  {
                Note cn = new Note();
                cn.Title = o.Decription_Opportunity__c;
                cn.body = o.Description;
                cn.ParentId = o.Id;         
                notes.add(cn);
            }//end of if
        }//end of for
        if (notes.size() >0) insert notes;
    }//end of if
}

メモ(Notes)の場合

困ったことにメモでは
本文のオブジェクトと、商談との関連を表すオブジェクトの2つに分かれています。

本文:ContentNoteオブジェクト
関係:ContentDocumentLinkオブジェクト

ContentDocumentLinkのLinkedEntityIdには商談のId
ContentDocumentIdには本文のIdをセットします。
また、ContentDocumentIdの実際の中身であるContentはBrob形式でエンコードしておく必要があるようです。

trigger UpdateContentDcomentLink on Opportunity (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
    if (Trigger.isAfter) {
        for(Opportunity o : Trigger.new) {
            if((Trigger.isInsert && o.Description!= null) || (Trigger.isUpdate && Trigger.oldMap.get(o.Id).Description != o.Description))  {
                ContentNote cn = new ContentNote();
                cn.Title = o.Decription_Opportunity__c;
                String body = o.Description;
                cn.Content = Blob.valueOf(body.escapeHTML4());
				insert(cn);   

                ContentDocumentLink cdl = new ContentDocumentLink();
                cdl.ContentDocumentId = cn.Id;
                cdl.LinkedEntityId = o.Id;
                insert(cdl);
                
            }//end of if
        }//end of for
    }//end of if
}

これだと、一括処理に制限が出ます。おそらく商談を51件以上処理したら発生します。

元の質問
https://trailblazers.salesforce.com/answers?id=9064S000000DLHGQA4

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0