この記事では、Salesforce レコードに変更を加える前と変更を加えた後に、Trigger.old と Trigger.new の値がどのように使用されるかについて説明します。Trigger.old と Trigger.new はコンテキスト変数です。
トリガーを起動したレコードにアクセスするには、コンテキスト変数を使用します。たとえば、Trigger.new には、Insert トリガーまたは Update トリガーで挿入されたすべてのレコードが含まれます。Trigger.old には、Update トリガーでは更新される前の sObject の古いバージョン、または削除トリガーでは削除された sObject のリストが含まれます。
トリガーは、1つのレコードが挿入されたとき、または API や Apex を介して多数のレコードが一括で挿入されたときに実行されます。そのため、Trigger.new などのコンテキスト変数には、1 つのレコードのみ、または複数のレコードが含まれます。 Trigger.new を反復処理することで、個々の sObject を取得できます。
ユースケース
シナリオの例
根拠
その理由は、これらの 2 つのデータ構造によって保持されている値を理解するためです。
Trigger.old の値は、現在のトランザクションの前後 (ユーザ操作) で同じになります。 Trigger.new も同様です。
つまり、Trigger.old は更新後にワークフローによって新しく更新された項目を保持しません。ただし、手動でレコードを編集すると、トリガーが再び起動します (これは新しい「更新トランザクション」と見なされます)。 Trigger.old は、ワークフロールールによって前のトランザクションで更新された項目を保持します。
上記の例に戻ります。
ワークフローの更新後の Trigger.old の値には、ワークフローで更新された [説明] 項目が含まれません。
ワークフローの更新後の Trigger.new の値には、オブジェクトの作成時に設定された既存の項目とワークフローが更新した [説明] 項目が含まれます。
同じ項目を取得するには、ワークフロー項目自動更新が発生した後でデータベースをクエリする必要があります。
たとえば:
List<Account> accts = [Select Id, FieldUpdatedByWorkflow__c from Account where Id in : Trigger.old];
トリガーのサンプルを参照してください。
注: 取引先オブジェクトの作成に関するワークフロー項目自動更新を作成し、結果をデバッグログに表示します。
trigger testTrigger on Account (before update, after update, before insert, after insert)
{
if (Trigger.isBefore) {
System.debug('********Trigger values***********');
System.debug('***SFDC: Trigger.old is: ' + Trigger.old);
System.debug('***SFDC: Trigger.new is: ' + Trigger.new);
}
if (Trigger.isAfter) {
System.debug('********Trigger values***********');
System.debug('***SFDC: Trigger.old is: ' + Trigger.old);
System.debug('***SFDC: Trigger.new is: ' + Trigger.new);
}
}
000384697

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.