salesforce 零基礎學習(六十四)頁面初始化時實現DML操作


有的時候我們往往會遇到此種類似的需求:用戶在訪問某個詳細的記錄時,需要記錄一下什么時候哪個用戶訪問過此頁面,也就是說進入此頁面時,需要插入一條記錄到表中,表有用戶信息,record id,sObject name以及vf page name.但是對於salesforce,不允許在controller的構造函數中進行DML操作,此種情況推薦采用兩種方式實現此功能:

一.使用apex:page的action屬性

1. DetailGoodsUseAjaxToolkitController:實現數據的初始化以及提供方法實現log記錄的插入操作

 1 public with sharing class DetailGoodsUseAjaxToolkitController {
 2     
 3     public DetailGoodsUseAjaxToolkitController() {
 4         initData();
 5     }
 6     
 7     private Map<String,String> params;
 8     
 9     public Goods__c goods{get;set;}
10     
11     private void initData() {
12         params = ApexPages.currentPage().getParameters();
13         String goodsId = params.get('id'); 
14         goods = [SELECT Goods_Code_Unique__c, GoodsBrand__c, GoodsCostPrice__c, GoodsDescribe__c,
15                          GoodsName__c, GoodsPrice__c, GoodsProfit__c,Id FROM Goods__c 
16                          where id=:goodsId];
17     }
18     
19     
20     /*
21     * 用於apex:page綁定的action,執行完構造函數以后執行此方法
22     */
23     public void createLog() {
24         Log_Info__c log = new Log_Info__c();
25         log.Access_Date__c = system.now();
26         PageReference pr = ApexPages.currentPage();
27         String relatedURL = pr.getUrl();
28         Integer startIndex = relatedURL.lastIndexOf('/') + 1;
29         Integer endIndex = relatedURL.indexOf('?') == -1 ? relatedURL.length() : relatedURL.indexOf('?');
30         String pageName = relatedURL.substring(startIndex,endIndex);
31         log.Access_Page__c = pageName;
32         log.Accessor__c = UserInfo.getUserId();
33         insert log;
34     }
35 }

2.DetailGoodsUseAction.page:實現頁面繪畫以及通過action調用后台方法實現DML操作

 1 <apex:page controller="DetailGoodsUseAjaxToolkitController" action="{!createLog}">
 2     <apex:form > 
 3         <apex:pageBlock title="Goods Information"> 
 4             <apex:pageBlockSection title="Goods Basic Information"> 
 5                 <apex:outputText id="GoodsUniqueCode" value="{!goods.Goods_Code_Unique__c}"/>
 6                 <apex:outputText id="GoodsName" value="{!goods.GoodsName__c}"/> 
 7                 <apex:outputText id="GoodsPrice" value="{!goods.GoodsPrice__c}"/> 
 8                 <apex:outputText id="GoodsCostPrice" value="{!goods.GoodsCostPrice__c}"/> 
 9             </apex:pageBlockSection> 
10         </apex:pageBlock> 
11     </apex:form> 
12 </apex:page>

二.使用ajax toolkit

 ajax toolkit API : https://resources.docs.salesforce.com/204/latest/en-us/sfdc/pdf/apex_ajax.pdf

相關核心API:https://developer.salesforce.com/docs/atlas.en-us.204.0.api.meta/api/sforce_api_calls_list.htm

ajax toolkit基於SOAP 的API,簡單的說即通過js調用soap api實現少量的數據的頁面展示或者對少量數據進行DML操作,如果對於大數據處理,別使用此種方式。

 使用ajax toolkit主要三個步驟:

1.Connecting to the API :

  針對非自定義button的引入

<apex:page> 
    <script src="../../soap/ajax/38.0/connection.js" type="text/javascript"></script> 
    <script> 
        sforce.connection.sessionId='{!GETSESSIONID()}'; 
        ... 
    </script> 
    ... 
</apex:page>

針對自定義onclick javascript按鈕的引入:

<body> 
    {!requireScript("/soap/ajax/38.0/connection.js")} ... 

2.Embedding API Calls in JavaScript :在javascript中嵌入API,然后通過回掉函數進行函數成功或者失敗的處理操作;

3.Processing Results:對結果進行處理。 如果進行的是查詢操作,可以對查詢列表進行相關處理或者執行queryMore等操作,如果是進行DML操作可以判斷是否執行成功等。

使用Ajax Toolkit可以實現同步或者異步的調用,詳情參看上方PDF。

 官方demo如下:

 1 <apex:page > 
 2     <script type="text/javascript"> 
 3         var __sfdcSessionId = '{!GETSESSIONID()}';
 4     </script> 
 5     <script src="../../soap/ajax/38.0/connection.js" type="text/javascript"></script> 
 6     <script type="text/javascript"> 
 7         window.onload = setupPage; 
 8         function setupPage() { //function contains all code to execute after page is rendered 
 9             var state = { //state that you need when the callback is called 
10                 output : document.getElementById("output"), 
11                 startTime : new Date().getTime()
12             }; 
13             var callback = { //call layoutResult if the request is successful 
14                 onSuccess: layoutResults, //call queryFailed if the api request fails 
15                 onFailure: queryFailed, 
16                 source: state
17             };
18             sforce.connection.query( "Select Id, Name, Industry From Account order by Industry", callback);
19         } 
20 
21         function queryFailed(error, source) { 
22             source.output.innerHTML = "An error has occurred: " + error; 
23         } 
24         /** * This method will be called when the toolkit receives a successful 
25         * response from the server. 
26         * @queryResult - result that server returned 
27         * @source - state passed into the query method call. 
28         */ 
29         function layoutResults(queryResult, source) { 
30             if (queryResult.size > 0) { 
31                 var output = ""; //get the records array 
32                 var records = queryResult.getArray('records'); //loop through the records and construct html string 
33                 for (var i = 0; i < records.length; i++) { 
34                     var account = records[i]; 
35                     output += account.Id + " " + account.Name + " [Industry - " + account.Industry + "]<br>"; 
36                 } //render the generated html string 
37                 source.output.innerHTML = output; 
38             } 
39         } 
40     </script>
41 
42     <div id="output"> </div> 
43 </apex:page>

通過demo可以看出:通過api先進行query操作查出Industry表數據,然后進行callback回掉,callback執行success和error的相關處理從而實現數據的展示。

通過ajax toolkit實現log數據的插入

 1 <apex:page controller="DetailGoodsUseAjaxToolkitController">
 2     <apex:form > 
 3         <apex:pageBlock title="Goods Information"> 
 4             <apex:pageBlockSection title="Goods Basic Information"> 
 5                 <apex:outputText id="GoodsUniqueCode" value="{!goods.Goods_Code_Unique__c}"/>
 6                 <apex:outputText id="GoodsName" value="{!goods.GoodsName__c}"/> 
 7                 <apex:outputText id="GoodsPrice" value="{!goods.GoodsPrice__c}"/> 
 8                 <apex:outputText id="GoodsCostPrice" value="{!goods.GoodsCostPrice__c}"/> 
 9             </apex:pageBlockSection> 
10         </apex:pageBlock> 
11     </apex:form> 
12     
13     <script type="text/javascript"> 
14         var __sfdcSessionId = '{!GETSESSIONID()}';
15     </script> 
16     <script src="/soap/ajax/38.0/connection.js" type="text/javascript"></script> 
17     <script src="/soap/ajax/38.0/apex.js" type="text/javascript"></script> 
18     <script type="text/javascript"> 
19         window.onload = setupPage; 
20         function setupPage() { 
21             var logInfo = new sforce.SObject("Log_Info__c");
22             logInfo.Accessor__c = "{!$User.Id}";
23             var accessDate = new Date("{!NOW()}");
24             logInfo.Access_Date__c = accessDate;
25             logInfo.Access_Page__c = "{!$CurrentPage.Name}";
26             var result = sforce.connection.create([logInfo]);
27             if (result[0].getBoolean("success")) { 
28                 //do success process
29             } else { 
30                 //do error process
31             }  
32         } 
33     </script>
34 </apex:page>

此種方式運行效果:

1.Log_Info__c最開始沒有任何數據

2.訪問當前頁面

3.訪問頁面后數據庫便存儲了一條當前訪問者訪問的頁面的Log數據

注意:此種方式對於谷歌瀏覽器會有一個問題,使用谷歌瀏覽器訪問會出現Refused to set unsafe header "User-Agent",解決方式可以為下載connection.js注釋掉關於User-Agent的處理,然后上傳到static resources中,在VF page引入static resource而不是系統的connection.js即可

 總結:此種類似需求其實可以很多種方式實現,此處只是使用兩種方式實現。第一種方式簡單粗暴,而且兼容性好,第二種方式只是起到拋磚引玉的效果,關於ajax toolkit什么時候使用以及限制等請自行查看上方PDF。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM