AJAX Toolkit

오픈소스 비즈니스 컨설팅
이동: 둘러보기, 검색

세일즈포스닷컴에서 제공하는 AJAX Toolkit을 정리한다.

Ajax Toolkit

  • AJAX Toolkit
<script type="text/javascript">
var __sfdcSessionId = "{!GETSESSIONID()}";
</script>
<apex:includeScript value="/soap/ajax/22.0/connection.js"/>
<apex:includeScript value="/soap/ajax/22.0/apex.js"/>  

<script type=“text/javascript”>
sforce.connection.init(null, “{!URLFOR(‘/services/Soap/u/13.0’)}"); 
sforce.connection.login(아이디, 암호);

var result = sforce.connection.query(
     “select Id from Account where ~ order by ~ limit ~ ");
var records = result.getArray("records");
for (var i=0; i< records.length; i++) {
    var record = records[i]; 
}
</script> 

var account = new sforce.SObject("Account");
account.type = “Account”;
account.Name = "my new account";
var result = sforce.connection.create([account]);
if (result[0].getBoolean("success")) { 
} else { 
}

result = sforce.connection.update([account]);
if (result[0].getBoolean("success")) {
} else {
}

var delResult = sforce.connection.deleteIds([account.Id]); 
if (delResult[0].getBoolean("success")) {
} else {
}
  • Debug 모드 설정
sforce.debug.trace = true;
sforce.debug.log("남길 로그");

Browser - jQuery

  • jQuery 사용 사례
<apex:page>
<apex:includeScript value="{!URLFOR($Resource.jQuery, 'jquery.min.js')}"/>

<apex:stylesheet value="{!URLFOR($Resource.ExtJS40, 'resources/css/ext-all.css')}"/>
<apex:includeScript value="{!URLFOR($Resource.ExtJS40, 'ext-all.js')}"/>
<apex:includeScript value="{!URLFOR($Resource.ExtJS40, 'locale/ext-lang-ko.js')}"/> 

<script type="text/javascript">
Ext.onReady(function() {
    Ext.Msg.alert(“pnus", "Hello World!");
});
</script>
</apex:page>

Browser - Ext-JS

  • Ext JS 4.0.1
  • Ext-JS 사용 사례
<apex:page>
<apex:includeScript value="{!URLFOR($Resource.jQuery, 'jquery.min.js')}"/>

<apex:stylesheet value="{!URLFOR($Resource.ExtJS40, 'resources/css/ext-all.css')}"/>
<apex:includeScript value="{!URLFOR($Resource.ExtJS40, 'ext-all.js')}"/>
<apex:includeScript value="{!URLFOR($Resource.ExtJS40, 'locale/ext-lang-ko.js')}"/>

<script type="text/javascript">
Ext.onReady(function() {
    Ext.Msg.alert(“pnus", "Hello World!");
});
</script>
</apex:page>

Apex API

SControl이나 JavaScript에서 사용할 수 있는 Apex API는 다양한 기능이 많이 있지만 여기서는 아주 간단히 조회/등록/수정/삭제 부분만 정리를 한다.

  • 공통 사항
Apex API를 사용하기 위해서는 다음을 반드시 포함하여야 한다.
 <script type="text/JavaScript" src="/soap/ajax/13.0/connection.js"></script>
 <script type="text/JavaScript" src="/soap/ajax/13.0/apex.js"></script>
  • VisualForce Page에서 사용하기 위해서 다음과 같이 선언 한다.
<apex:page showHeader="false" >
    <script src="../../soap/ajax/21.0/connection.js"></script>
</apex:page>
  • Debug 모드 설정
Apex API를 호출하기 전에 sforce.debug.trace를 true로 설정한다.
이후 Debug 창에 로그가 남으며 사용자 로그를 남기고 싶을 경우에는 sforce.debug.log() 함수를 사용한다.
 sforce.debug.trace = true;
 sforce.debug.log("남길 로그");
  • 로그인
SControl에서 사용할 경우에는 로그인이 필요 없지만 기타 환경에서는 로그인을 하여 세일즈포스닷컴에 접속한다.
  sforce.connection.init(null, "https://emea.salesforce.com/services/Soap/u/13.0");
  sforce.connection.login(아이디, 암호);
  • 조회 (동기식)
 var result = sforce.connection.query(“select Id from Account where ~ order by ~ limit ~ ");
 records = result.getArray("records");
 for (var i=0; i< records.length; i++) {
     var record = records[i];
     window.alert(record.Id);
 }
  • 조회 (비동기식)
 var callback = {
     onSuccess : funcSuccess,
     onFailure : funcFailure,
     source : {}
 };
 sforce.connection.query(“select Id from Account where ~ order by ~ limit ~ “, callback);

 function funcSuccess(result, source) {
     //--- 여기에 조회가 성공하였을 때 필요한 코딩을 한다.
 }
 function funcFailure(error, source) {
     //--- 여기에 조회가 실패하였을 때 필요한 코딩을 한다.
 }
  • 등록 (표준 개체)
 var account = new sforce.SObject("Account");
 account.Name = "my new account";
 var result = sforce.connection.create([account]);
 if (result[0].getBoolean("success")) {
 } else {
 }
  • 등록 (사용자 정의 개체)
 var obj= new sforce.SObject();
 obj.type = “KnowledgeForce__c”;
 obj.Name = "my new Knowledge";
 var result = sforce.connection.create([obj]);
  • 수정
 var account = new sforce.SObject("Account");
 account.Name = "myName";
 account.Phone = "2837484894";
 result = sforce.connection.create([account]);

 account.id = result[0].id;
 account.Phone = "12398238";
 result = sforce.connection.update([account]);
 if (result[0].getBoolean("success")) {
     log("account with id " + result[0].id + " updated");
 } else {
     log("failed to update account " + result[0]);
 }
  • 삭제
 var delResult = sforce.connection.deleteIds([account.Id]);
 if (delResult[0].getBoolean("success")) {
     log("account with id " + result[0].id + " deleted");
 } else {
     log("failed to delete account " + result[0]);
 }

AJAX Toolkit Developer's Guide, Ver 9.0 Spring'07

  • Data Types
   Date            : getDate, getDateTime
   Int             : getInt
   Float           : getFloat
   Boolean         : getBoolean
   Array           : getArray
   getBase64Binary
  • Sample AJAX
   <script src="/js/dojo/0.3.1/dojo.js" type="text/JavaScript"></script>
   <script src="/soap/ajax/9.0/connection.js" type="text/JavaScript"></script>

   try {
       sforce.connection.login("~", "~");
       sforce.debug.open();
       sforce.debug.log("~");
   } catch(error) {
       error.faultcode.indexOf("INVALID_LOGIN")
   }

   result = sforce.connection.query("~ limit 30");
   records = result.getArray("records");

   sforce.connection.query("~ limit 30", {onSuccess:handleSuccess, onFailure:handleFailure});
   //---   handleSuccess(result), onFailure(error)

   var result = sforce.connection.search("find {manoj} in Name fields RETURNING Account (name, id)");

   var data = new sforce.QueryResultIterator(result);
   data.hasNext();
   var record = data.next();

   account.Name
   account["Name"]

   var account = new sforce.SObject("Account");
   var result = sforce.connection.create([account]);
   sforce.connection.update([account.Id]);
   sforce.connection.upsert("Id", [account]);
   sforce.connection.deleteIds([account.Id]);
   sforce.connection.undelete([account.Id]);
   result[0].getBoolean("success");

   var req = new sforce.MergeRequest();
   req.masterRecord = account1;
   req.recordToMergeIds = account2.id;
   result = sforce.connection.merge([req]);

   result = sforce.connection.retrive("Name, Phone", "Account", [result[0].id]);

   var result = sforce.connection.getDeleted("Account", startDate, endDate);
   var result = sforce.connection.getUpdated("Account", startDate, endDate);

   var convert = new sforce.LeadConvert();
   convert.accountId = account.Id;
   convert.leadId = lead.Id;
   convert.convertedStatus = "Qualified");
   result = sforce.connection.convertLead([convert]);

   sforce.connection.getServerTimestamp();
   sforce.connection.getUserInfo();

   var result sforce.connection.query("~ like '~%~'", {onSuccess:funcSuccess, onFailure:funcFailure, timeout:100});

   -   Describe (Page 20 참조)
  • 메일 발송
   var req = new sforce.SingleEmailMessage();
   req.replyTo = "~";
   req.subject = "~";
   req.plainTextBody = "~";
   req.toAddresses = ["~"];

   var tmpRes = sforce.connection.query("select id form emailtemplate");
   var templateId = tmpRes.getArray("records")[0].Id;
   var massReq = new sforce.MassEmailMessage();
   massReq.targetObjectIds = [globalContact.id];
   massReq.replyTo = "~";
   massReq.subject = "~";
   massReq.templateId = templateId;

   var sendMailRes = sforce.connection.sendEmail([req, massReq]);
  • Debug
sforce.debug.log(myVar);
sforce.debug.open();
  • Select
  • query
   result = sforce.connection.query("Select Name, Id from User");
   records = result.getArray("records");
   for (var i=0; i< records.length; i++) {
       var record = records[i];
       log(record.Name + " -- " + record.Id);
   }
  • queryMore
   var result = sforce.connection.query("select name, id from account");
   var queryMore = true;
   while (queryMore) {
       var records = result.getArray("records");
       var sb = new sforce.StringBuffer();
       for (var i = 0; i < records.length; i++) {
           sb.append(records[i].Name).append(",");
       }
       log(records.length);
       log(sb.toString());
       if (result.getBoolean("done")) {
           queryMore = false;
       } else {
           result = sforce.connection.queryMore(result.queryLocator);
       }
   }
  • queryAll
   var result = sforce.connection.queryAll("Select Name, Id from Account");
   var records = result.getArray("records");
   for (var i=0; i<records.length; i++) {
       var record = records[i];
       log(record.Name + " -- " + record.Id);
   }
  • Relationship Query Example--Child to Parent
   var result = sforce.connection.query("SELECT c.Id, c.firstname, " +
       "c.lastname, c.leadsource, a.Id, a.name, a.industry, c.accountId " +
       "FROM Contact c, c.account a ORDER BY leadsource LIMIT 10");
   var it = new sforce.QueryResultIterator(result);
   while(it.hasNext()) {
       var record = it.next();
       var accountName = record.Account ? record.Account.Name : null;
       log( record.FirstName + " " + record.LastName + " in account " + accountName);
   }    
  • Relationship Query Example--Parent to Child
   var result = sforce.connection.query("select a.Name, a.Industry, " +
       "(select c.LastName, c.LeadSource from a.Contacts c) " +
       "from account a order by industry limit 100");
   var ait = new sforce.QueryResultIterator(result);
   while(ait.hasNext()) {
       var account = ait.next();
       var contacts = [];
       if (account.Contacts) {
           var cit = new sforce.QueryResultIterator(account.Contacts);
           while(cit.hasNext()) {
               var contact = cit.next();
               contacts.push(contact.LastName);
           }
       }
       log(account.Name + ": " + contacts.join(","));
   }    
  • Insert
  • create
   var account = new sforce.SObject("Account");
   account.Name = "my new account";
   var result = sforce.connection.create([account]);
   if (result[0].getBoolean("success")) {
       log("new account created with id " + result[0].id);
   } else {
       log("failed to create account " + result[0]);
   }
  • Batch create
   var accounts = [];
   for (var i=0; i<10; i++) {
       var account = new sforce.SObject("Account");
       account.Name = "my new account " + i;
       accounts.push(account);
   }

   var result = sforce.connection.create(accounts);
   for (var i=0; i<result.length; i++) {
       if (result[i].getBoolean("success")) {
           log("new account created with id " + result[i].id);
       } else {
           log("failed to create account " + result[i]);
       }
   }
  • Update
   var account = new sforce.SObject("Account");
   account.Name = "myName";
   account.Phone = "2837484894";
   result = sforce.connection.create([account]);

   account.id = result[0].id;
   account.Phone = "12398238";
   result = sforce.connection.update([account]);
   if (result[0].getBoolean("success")) {
       log("account with id " + result[0].id + " updated");
   } else {
       log("failed to update account " + result[0]);
   }
  • Delete
   var account = new sforce.SObject("Account");
   account.Name = "my new account";
   var result = sforce.connection.create([account]);
   if (result[0].getBoolean("success")) {
       log("new account created with id " + result[0].id);
       account.Id = result[0].id;
   } else {
       throw ("failed to create account " + result[0]);
   }

   //now delete the example account
   var delResult = sforce.connection.deleteIds([account.Id]);
   if (delResult[0].getBoolean("success")) {
       log("account with id " + result[0].id + " deleted");
   } else {
       log("failed to delete account " + result[0]);
   }
  • Merge
   var account1 = new sforce.SObject("Account");
   account1.Name = "myName";
   account1.Phone = "2837484894";
   var account2 = new sforce.SObject("Account");
   account2.Name = "anotherName";
   account2.Phone = "938475950";
   var result = sforce.connection.create([account1, account2]);
   if (result.length != 2) throw "create failed";

   account1.id = result[0].id;
   account2.id = result[1].id;
   //create merge request
   var request = new sforce.MergeRequest();
   request.masterRecord = account1;
   request.recordToMergeIds = account2.id;
   //call merge
   result = sforce.connection.merge([request]);
   if (result[0].getBoolean("success")) {
       log("merge success " + result[0]);
   } else {
       log("merge failed " + result[0]);
   }

Apex Code JavaScript

  • Setup -> App Setup -> Build -> Code
  • Setup -> App Setup -> Customize -> [Accounts] -> Buttons and Links -> Custom Buttons and Links
  • AJAX
<script type="text/JavaScript" src="/soap/ajax/12.0/connection.js"></script>
<script type="text/JavaScript" src="/soap/ajax/12.0/apex.js"></script>
    sforce.apex.executeAnonymous(<script>);
    sforce.apex.execute("myPackage", "makeContact", {a:Smith, b:account});
    sforce.debug.trace = true;

var result = sforce.apex.execute('HelloWorld2' , 'sayHelloWorld', {arg:"new Apex Code user!"});
sforce.apex.debug=true;

var request = new sforce.RunTestsRequest();
request.allTests = false;
request.classes = ['HelloWorld2'];
var result_2= sforce.apex.runTests(request);

참고 문헌

지원 업체

SuiteCRM을 사용한 영업관리, 고객관리는 아래 담당자에게 연락하여 주시면, 빠르고 친절하게 전문적인 답변을 드리겠습니다.

영업 문의 sales@obcon.biz 010-4667-1106 영업 대표
기술 문의 tech@obcon.biz 구축/컨설팅 담당
고객 지원 support@obcon.biz 고객 지원 담당

OBCon 홈페이지 바로가기