レコードを作成し、Web サービスから提供された情報で更新する必要がある場合があります。しかし、同じトランザクション内で DML ステートメントの後に Web サービスコールアウトを試みると「You have uncommitted work pending. Please commit or rollback before calling out」エラーが発生します。必要な処理を実現するには、トランザクションを 2 つに分割し、Web サービスコールアウトが発生する前に DML ステートメントを含むトランザクションを完了する必要があります。
最初のプロセスはレコードを挿入し、2 番目のプロセスはコールアウトを実行して、新しく挿入されたレコードを更新できます。
Visualforce ページ: TestWsCallout
<apex:page controller="TestWsCallout" tabstyle="Account">
<apex:form >
<apex:actionFunction action="{!InsertRecord}" name="InsertRecord_JS" Rerender="statuses" status="Status1" oncomplete="CallWebService_JS();"/>
<apex:actionFunction action="{!CallWebService}" name="CallWebService_JS" status="Status2" reRender="statuses, msg"/>
<apex:outputPanel id="statuses">
<apex:actionStatus id="Status1" startText="...Inserting Record Into DB..." />
<apex:actionStatus id="Status2" startText="...Calling Web Service..." />
</apex:outputPanel>
<apex:outputPanel id="msg">
<apex:pageMessages />
</apex:outputPanel>
<div><input name="DoAction" class="btn" type="button" value="Do Action" onclick="InsertRecord_JS();return false;"/></div>
</apex:form>
</apex:page>
Apex コントローラー: TestWsCallout
public class TestWsCallout{
Account myAccount;
public PageReference InsertRecord() {
myAccount = new Account(name = 'Test Account');
insert myAccount;
// この部分にコールアウト処理を入れると表題のエラーが出ます。
return null;
}
public PageReference CallWebService() {
// Web サービスのコールを実行
HttpRequest req = new HttpRequest();
req.setEndpoint('http://MyWebService12345678790.com?id=' + myAccount.Id);
req.setMethod('GET');
HttpResponse response = new Http().send(req);
// レコードを更新
myAccount.Name = 'Test Account 2';
update myAccount;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'WebService Called on New Account: ' + myAccount.Name));
return null;
}
}
000385374

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.