[Salesforce]必須チェック範囲

Salesforceの必須チェック範囲について共有します。

1.項目設定で必須にした場合

必須チェック範囲:

ページレイアウトからデータ登録・更新

データローダからデータ登録・更新

Apexクラスからデータ登録・更新

2.ページレイアウトで必須にした場合

必須チェック範囲:

ページレイアウトからデータ登録・更新

[Salesforce]スケジュールバッチのトランザクション処理順

スケジュールバッチのトランザクション処理順について共有します。

例えば、10件のデータを1トランザクション毎2件ずつ処理するようになります。

その処理は直列で実行されます。

以下の例で確認できます。

global class SampleBatch implements Database.Batchable<sObject> {
  
  // The batch job starts
  global Database.Querylocator start(Database.BatchableContext bc){
    String query = 'SELECT Id, Name FROM Account LIMIT 100';
    return Database.getQuerylocator(query);
  } 
  
  // The batch job executes and operates on one batch of records
  global void execute(Database.BatchableContext bc, List<sObject> scope){
    System.debug(LoggingLevel.INFO, '>>> execute start at ' + DateTime.now().format('yyyy/MM/dd hh:mm:ss'));
    Long startTime = DateTime.now().getTime();
    Long finishTime = DateTime.now().getTime();
    
    while ((finishTime - startTime) <= 2000) {
      //sleep 2s
      finishTime = DateTime.now().getTime();
    }
    
    System.debug(LoggingLevel.INFO, '>>> execute end at ' + DateTime.now().format('yyyy/MM/dd hh:mm:ss'));
  }
  
  // The batch job finishes
  global void finish(Database.BatchableContext bc){
    AsyncApexJob job = [SELECT Id, Status FROM AsyncApexJob WHERE Id = :bc.getJobId()]; 
    System.debug(LoggingLevel.INFO, '>>>> finish ' + job.Status);
  }
}

バッチ実行

Integer BATCH_SIZE = 2;
SampleBatch sb = new SampleBatch();
Database.executeBatch(sb, BATCH_SIZE);

[Salesforce]@RemoteAction

Salesforceの @RemoteAction について共有します。

特徴

・ JavaScriptからApexクラスの処理を実行できます。

・ actionFunctionと同じような機能ですが、こちらはJavaScript内で処理の戻り値を使用できます。

例えば取引先取得処理を実行して取得した取引先リストを使用した処理を行うことができます。

サンプルコード

・Apexクラス

 global with sharing class SampleRemoteController {
    @RemoteAction
    global static String setString(String str) {
        return  '----- ' + str + ' -----';
    }
    
    @RemoteAction
    global static List<sObject> exequery(String str){
        return Database.query(str);
    }
} 

・Visualforceページ

 <apex:page controller="SampleRemoteController">
    <apex:form >
        <!-- @RemoteActionSample:StringSet -->
        <apex:commandButton value=" String " onClick="return  setString('Yaho');" />
         
        <!-- @RemoteActionSample:SOQLGet -->
        <apex:commandButton value=" GetAcc " onClick="return getAcc();" />
        <hr/>
        <div id="output">Output</div>
    </apex:form>

    <script type="text/javascript">
        /*
         * @RemoteActionSample
         * StringSet
         */
        function setString(str) {
            {!$RemoteAction.SampleRemoteController.setString}(str, function(result, event){
                if(event.status) {
                    document.getElementById("output").innerHTML = result;
                }
            });
            return false;
        }
        
        /*
         * @RemoteActionSample
         * SOQLAccountGet
         */
        function getAcc() {
            var query = 'select Id,Name from Account limit 10';
            {!$RemoteAction.SampleRemoteController.exequery}(query, function(result, event){
                if(event.status) {
                    var names = '';
                    for (var i = 0; i < result.length; i++) {
                        names = names + result[i].Name + ' | ';
                    }
                    document.getElementById("output").innerHTML = names;
                }
            });
            return false;
        }
    </script>
</apex:page>                     

[Salesforce]ビューステート

Salesforceのビューステートについて共有します。

・ Apexコントローラの状態やVisualforceページの状態をサーバリクエスト間も保持するための、Visualforceページ内に暗号化されたhiddenのinputフィールドのこと。

このフィールドはapex:formタグがページ上にある場合のみ生成される。

・Salesforce で許容される Visualforce ページの最大ビューステートサイズは 135KB です。

・[View State (ビューステート)] タブには、ページのどの要素がその領域を占めているかが表示されます。

一般に、ビューステートサイズが小さいほど読み込み時間が短くなります。

回避策

・ ページのビューステートを最小に設定します。

・ Apex コントローラコードを最適化し、使用される余分な Visualforce コンポーネントを削除する

・ Visualforce ページに関連するデータのみを返すことを検討

Salesforceにて、ビューステートを確認する手順

・ユーザの以下の項目にチェックをつける。

  開発モード

  開発モードでビューステートを表示

・Visualforceページを表示し、画面下の開発モードを表示させる。

・「view state」ボタン押下して、「Size(KB)」列を確認する。

[Salesforce]監視debugレベル

Salesforce開発時に監視debugレベルによって監視したい範囲を絞ることができる。

今回は、debugレベルは以下にした。

「 Apex コード」レベルのみを「INFO 」にて、その他のカテゴリはすべてなしに設定することで、余計な監視情報を表示しないで、監視したい情報を絞ることができます。

<カテゴリ> <レベル>
データベース NONE
ワークフロー NONE
入力規則 NONE
コールアウト NONE
Apex コード INFO
Apex プロファイリング NONE
Visualforce NONE
システム NONE
Wave NONE
Next Best Action NONE

ApexでのDebugコードは以下にした。

System.debug(LoggingLevel.INFO, ‘—-debugData:’ + debugData);

[Salesforce]Queueable インターフェース

Queueable インターフェースについて共有します。

特徴

・ジョブの監視可

・2つのジョブの連続的な処理可

使用方法

・ Queueable クラス作成

public class MyQueueableClass implements Queueable {

以下はメソッド

public void execute(QueueableContext context) {
    // Your code here
}

・ Queueable クラス呼び出し

ID jobID = System.enqueueJob(new MyQueueableClass());

・ Queueable クラス作成

public class AsyncExecutionExample implements Queueable {     
    public void execute(QueueableContext context) {         
        Account a = new Account(Name='Acme',Phone='(415) 555-1212'); 
        insert a;             
    } 
} 

・ Queueable クラス呼び出し

ID jobID = System.enqueueJob(new AsyncExecutionExample());

・ジョブ監視

AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];

・テストクラス

@isTest
public class AsyncExecutionExampleTest {
    static testmethod void test1() {
        // startTest/stopTest block to force async processes 
        //   to run in the test.
        Test.startTest();        
        System.enqueueJob(new AsyncExecutionExample());
        Test.stopTest();
        
        // Validate that the job has run
        // by verifying that the record was created.
        // This query returns only the account created in test context by the 
        // Queueable class method.
        Account acct = [SELECT Name,Phone FROM Account WHERE Name='Acme' LIMIT 1];
        System.assertNotEquals(null, acct);
        System.assertEquals('(415) 555-1212', acct.Phone);
    }
}

[Salesforce]mapクラスのkeysetメソッド

SalesforceのmapクラスのkeySetメソッドについて共有します。

対応付けのすべてのキーを含むセットを返します。

Map<String, String> colorCodes = new Map<String, String>();

colorCodes.put('Red', 'FF0000');
colorCodes.put('Blue', '0000A0');

Set <String> colorSet = new Set<String>();
colorSet = colorCodes.keySet();
System.debug('colorSet:'+colorSet); 

結果

colorSet:{Blue, Red}

[Salesforce]removeメソッド

SalesforceのStringリストのメソッドremoveについて共有します。

remove(index)

指定されたインデックスに保存されたリスト要素を削除し、削除された要素を返します。

List<String> colors = new String[3];
colors[0] = 'Red';
colors[1] = 'Blue';
colors[2] = 'Green';
String s1 = colors.remove(2);
system.assertEquals('Green', s1);

[Salesforce]sfdxによる開発

0.visual studio codeをインストールする。

https://code.visualstudio.com/?wt.mc_id=DX_841432

1.Salesforce CLI インストール

https://developer.salesforce.com/docs/atlas.ja-jp.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm

ダウンロードして、インストールする。

2.1.をインストールしたら、コマンドプロンプトで以下のコマンドインストールを確認する。

sfdx plugins --core

3.vs codeに拡張機能をインストールする。

https://marketplace.visualstudio.com/items?itemName=salesforce.salesforcedx-vscode

4.ローカルにプロジェクトを作成

vs codeを起動する。

表示 → コマンドパレット → sfdx: Create Project with Manifestを選択→フォルダ名入力(例えば、testproject)→Enterキー押下

選択すると、ローカル画面が表示される。

例えば、入力したフォルダ名を置くフォルダを選択、例えば「Project」ファルダを選択してして、「プロジェクト作成」ボタン押下する。

5.Salesforce組織とつなげる。

vs code画面にて、表示 → コマンドパレット → sfdx: Authorize an Org選択する。

Production/Sandboxどちらを選択する。

Salesforceログイン画面が表示されるが、ログインする。

6.メータデータ取得

vs codeにて、package.xmlの右クリックして、SFDX: Retrieve Source from Org選択する。

するとメータデータを取得される。

7.ソースコードを組織にDeploy

該当ソースコードに変更し、右クリックして、SFDX: Deploy from to Orgを選択する。

SalesforceのユーザIDを入力する欄があるので、入力する。

[Salesforce]vscodeのforcecode拡張で開発手順

vscodeのforcecode拡張で開発手順

1.vscodeインストールする。

https://code.visualstudio.com/download

2.forcecode拡張インストール

vscode起動して、左サイドメニュー「Extentions」押下する。

検索欄に「forcecode」を入力して、「install」ボタン押下する。

3.メニュー → 表示 → コマンド パレット → ForceCode: Create Project押下

フォルダー選択画面が開くので、フォルダーを作成する。

例えば、C:\workspace\TestProject

C:\workspace直下に、TestProjectフォルダーを作成し、TestProjectフォルダーにて、「Create Project」ボタン押下する。

4.vscodeに戻るので、戻ると、New Org押下 → Production / Sandbox選択する。

Salesforceログイン画面が開くので、ユーザ名とパスワードを入力し、「ログイン」ボタン押下する。

5.vscode画面にて、 メニュー → 表示 → コマンド パレット → ForceCode: Get Class, Page or Trigger 押下する。

取得するモジュールをチェックして、「OK」ボタン押下する。

6.例えば、編集したクラスを表示して編集し、保存する。

組織にて反映されていることを確認する。

7.組織にて、編集したいクラスを表示して編集し、保存する。

vscodeにて、該当クラスにて、マウス右クリックして、「Forcecode: Refresh From Server」押下して、反映されているこを確認する。