LoginSignup
7
6

More than 1 year has passed since last update.

Salesforce DXとSalesforce CLIの入門練習ガイド

Posted at

この記事ではsalesforce開発において基礎知識とも言えるSFDXとSalesforce CLIを簡単に学んでいきたいと思います。この記事に通じて分かるようになる内容が以下となります。

・Salesforce DXとSalesforce CLIとは
・Salesforce CLIが必要な開発環境とツール
・CLIコマンドを覚える
・メタデータのデプロイと取得
・クエリ/アップロードなどデータの操作
・CLIの自動化

この記事でかなりの一部内容がManish Choudhariさんのgithubを参照しています。
https://github.com/choudharymanish8585

1.Salesforce DXとSalesforce CLIとは

1-2.Salesforce DXとは

Salesforce DXは外部のリポジトリでアプリケーションを管理して標準化や自動化を進め、Salesforce開発の生産性や管理品質を向上するための機能の総称です。

Salesforce DX提供する機能(一部)
・Scratch Orgs(スクラッチ組織) : コマンドから自由に作成・破棄できるSalesforce組織。
・Salesforce CLI : Scratch Orgsや項目の作成などSalesforce組織の管理が実行できるコマンドツール

1-3.Salesforce CLIとは

Salesforce CLI は、 Salesforce 組織を利用した開発およびビルドの自動化のためのパワフルなコマンドラインインタフェース

Salesforce CLI提供する機能(一部)
・Salesforce組織に対して開発時に必要なコマンドのツール群
・スクラッチ組織とのソースコードの双方向同期
・組織の作成及び管理
・データのインポート及びエクスポート
・テストの作成及び実行
・パッケージの作成及びインストール

2.Salesforce CLIが必要な開発環境とツール

この記事で使った開発ツール及び開発環境を紹介します。
OS:Windows 11 Pro
エディタ:VSCode
バージョン管理ツール:Git
その他:openssl(Win64 OpenSSL v1.1.1o)

2-1.VSCodeのダウンロードと拡張機能の実装

公式サイトはこちら( https://code.visualstudio.com )の URL です。では、さっそくこちらのボタンからダウンロードしていきましょう。

公式サイト

ダウンロードした後にインストールしましょう。

インストール完了後にActivity Barの拡張機能をクリックしましょう。
image.png
検索欄にsalesforceを入力し検索結果からSalesforce Extension Packをダウンロードしましょう。
image.png
これでVSCodeの設定が完了になりました。

2-2.gitのダウンロードとインストール

公式サイトはこちら( https://gitforwindows.org/ )の URL です。では、さっそくこちらのボタンからダウンロードしていきましょう。
image.png
ダウンロードした後にインストールしましょう。
image.png
ここだけ二番目に変えて他の選択肢をそのままnextをおしましょう

2-3.git bashの起動

これからはgit bashでlinuxコマンドを操作するのでCortanaの検索窓にgit bashと入力して検索すると出てきます。
image.png
起動して確かめるましょう。
image.png
無事に起動しました。

2-4.opensslのダウンロードとインストール

salesforce CLIの自動化にはopensslが必要なため公式サイト(https://slproweb.com/products/Win32OpenSSL.html) からダウンロードしましょう。
image.png

Ver. 3.0系列とVer. 1.1.1系列それぞれのインストーラーが公式から用意されている。前者は2021年にメジャーバージョンアップした最新版で、今は採用しているプラットフォームはまた多くないため1.1.1系列をおすすめします。
image.png
ダウンロードした後にインストールしましょう。
image.png

3.Salesforce CLIの準備

開発環境や開発ツールなどを整えました、いよいよSalesforce CLI本体の準備に入ります。

3-1.Salesforce CLIのダウンロードとインストール

Salesforce CLIを公式( https://developer.salesforce.com/ja/tools/sfdxcli )からダウンロードしましょう。
image.png

ダウンロードした後にインストールしましょう
image.png

3-2.CLIコマンドを実行してみよう

フォルダの位置が分かるようにワークスペースのフォルダを作成しましょう。
image.png

VSCodeを起動してフォルダーを開くをクリックしましょう。
image.png
先ほど作成したフォルダーを選択しましょう。
image.png
フォルダーを開いた後にVSCodeのステータスバーのエラーとバグの表示をクリック
image.png
クリックしてターミナルに切り替える
image.png

+隣の↓をクリックしてgit bashに切り替える

image.png
最初のCLIコマンドsfdx commandsを入力してください
image.png
CLIコマンド一覧が表示されました。
image.png

3-3.CLIコマンドの構成

CLIコマンドはNamespace,Topic,Subtopic,Commandこの四つの部分で構築されている。
command.png

3-3-1.Namespaceについて

CLIコマンドはNamespaceで始まり基本的にforceで書く

3-3-2.Topicについて

Namespaceの次の部分がTopic、これはApexやvisulaforceなど命令対象をしてする

3-3-3.Subtopicについて

Topicの次の部分はSubtopic、これは指示している対象のより具体的な部分を指している(例:page,doc)

3-3-4.Commandについて

最後の部分がCommand、具体的な命令を行う部分(例:create,delete)

3-3-5.CLIコマンドの操作関連一覧

CLIコマンドの操作関連一覧のドキュメントを見るには命令の最後に--help
以下が例とする

sfdx force:user:list --help

実行結果
image.png

4.SFDX プロジェクトについて

ここからはCLIコマンドを使うSFDXプロジェクト作成と関連作業するためのSalesforce組織の権限セットについて解説します。

4-1.SFDX プロジェクトの作成

作成命令のオプションについて調べよう

sfdx force:project:create --help

image.png

・-d フォルダーに作成したファイルを保存
・-n プロジェクト名を決める
・-p デフォルトパッケージのデレクトリ
・-s プロジェクト関連のnamespace
・-t プロジェクト作成にデフォルトテンプレートを使う
・-x 変更セット開発フォーマットのmanifestをjsonとして出力

さそっくプロジェクトを作ってみよう、manifestつきかつプロジェクト名をCLISessionとする

sfdx force:project:create -n CLISession -x

無事に生成出来ました
image.png
manifestの内容を確認しましょう。
image.png

自動化sampleの準備として以下の内容と入れ替えしましょう。

package.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
    <name>CustomApplication</name>
    <members>Tree_Plantation</members>
  </types>
  <types>
    <name>ApexClass</name>
    <members>TreeListController</members>
    <members>TreeListControllerTest</members>
    <members>TreeLocationController</members>
  </types>
  <types>
    <name>FlexiPage</name>
    <members>Tree_Plantation</members>
    <members>Tree_Plantation_UtilityBar</members>
  </types>
  <types>
    <name>Layout</name>
    <members>City__c-City Layout</members>
    <members>Tree_Plantation__c-Tree Layout</members>
    <members>Tree__c-Tree Layout</members>
  </types>
  <types>
    <name>LightningComponentBundle</name>
    <members>pubsub</members>
    <members>treeCard</members>
    <members>treeList</members>
    <members>treeLocation</members>
    <members>treePlantationExplorer</members>
  </types>
  <types>
    <name>CustomObject</name>
    <members>City__c</members>
    <members>Tree_Plantation__c</members>
    <members>Tree__c</members>
  </types>
  <types>
    <name>CustomField</name>
    <members>City__c.Location__c</members>
    <members>City__c.Target__c</members>
    <members>City__c.Total_Trees__c</members>
    <members>Tree_Plantation__c.Age__c</members>
    <members>Tree_Plantation__c.Number_Of_Tree_Planted__c</members>
    <members>Tree_Plantation__c.Planted_In__c</members>
    <members>Tree_Plantation__c.Tree__c</members>
    <members>Tree__c.Benefit__c</members>
    <members>Tree__c.Picture__c</members>
  </types>
  <types>
    <name>ListView</name>
    <members>City__c.All</members>
    <members>Tree_Plantation__c.All</members>
    <members>Tree__c.All</members>
  </types>
  <types>
    <name>PermissionSet</name>
    <members>TreePlantation</members>
  </types>
  <types>
    <name>StaticResource</name>
    <members>treeimages</members>
  </types>
  <types>
    <name>CustomTab</name>
    <members>City__c</members>
    <members>Tree_Plantation</members>
    <members>Tree_Plantation__c</members>
    <members>Tree__c</members>
  </types>
  <version>46.0</version>
</Package>

次にconfigのproject-scratch-def.jsonを確認しましょう。
image.png
変更して独自のスクラッチ組織定義ファイルを作成 。そして、"hasSampleData": true,を加えましょう。
image.png
これでデフォルト設定のようにサンプルデータ生成するようになりました。

4-2.salesforce組織の権限セット

ここからはsalesforce組織の権限セットを行うためにまずはログインをする。ログイン命令関連のオプションも調べよう

sfdx force:auth:web:login --help

image.png
・-a 認証済み組織に別称付ける
・-d 認証済み組織をスクラッチ組織のデフォルトdev hub組織にする
・-i OAuthクライアントID(consumer keyと呼ばれる場合もある)
・-r ログインURL指定
・-s デフォルトユーザー名セット

組織名をCLICourseDevHub としてデフォルトユーザー名セットしてloginしましょう。

sfdx force:auth:web:login -a CLICourseDevHub -s

image.png
ログイン画面が開いたらログインしましょう。成功しましたらブラウザを閉じても大丈夫です
image.png
.sfdxフォルダのsfdx-config.jsonにデフォルトユーザー名セットが成功したかを確かめましょう。
image.png
デフォルトDev Hubユーザー名もセットしましょう。

sfdx force:config:set defaultdevhubusername=CLICourseDevHub

無事に追加しました。
image.png
Salesforce では、開発中に最も頻繁に接続する組織のデフォルトのユーザ名を設定することをお勧めします。この作業は、Dev Hub 組織の認証時かスクラッチ組織の作成時に行うのが最も簡単です。プロジェクトディレクトリからそれぞれ --setdefaultdevhubusername または --setdefaultusername パラメータを指定します。別名を作成して、ユーザ名により読みやすい名前を付けることもできます。組織に接続するすべての CLI コマンドでユーザ名または別名を区別せずに使用できます。

5.CLIコマンド使うメタデータの働きについて

Metadata は、すべての標準オブジェクトを表す sObject に類似しています。Metadata は、メタデータ API ですべてのコンポーネントと項目を表します。各コンポーネントを ID で識別するのではなく、各カスタムオブジェクトまたはカスタム項目には一意の fullName があります。この名前は、Salesforce ユーザインターフェースでカスタムオブジェクトやカスタム項目を作成するときのために、標準オブジェクト名とは異なるものにする必要があります。ここではCLIコマンドを使うメタデータの操作を解説します。

5-1."mdapi"topicを使うメタデータの取得

まず、メタデータの取得ため今回に使う"mdapi"topicのコマンドについて調べる

sfdx force:mdapi --help

force:mdapi:convert メタデータをメタデータAPIフォーマットからソースフォーマットに切り替える
force:mdapi:deploy メタデータAPIを使いメタデータを組織にデプロイする
force:mdapi:retrieve メタデータAPIを使いメタデータを組織から取得する
image.png

実際に操作してみよう、先ずはCLISessionフォルダにmetadataフォルダを作成
image.png

次にmanifestとメタデータを取得しましょう。

sfdx force:mdapi:retrieve -k manifest/package.xml -r metadata/

-k コンポーネントのmanifestのファイルパスを取得
-r 取得ファイルのディレクトリ指定

image.png

image.png
無事にzipを取得しました、解凍しましょう。デフォルトパッケージのディレクトリではなく、先ほど作成したmetadataフォルダにしてください。

 unzip metadata/unpackaged.zip -d metadata/

image.png

次にunpackagedの内容をforce-appに入れ替えよう

 sfdx force:mdapi:convert -r metadata/unpackaged -d force-app

-r rootディレクトリ指定
-d 出力先のディレクトリ指定
image.png
metadataのclassesと同じものを確認できます。

5-2."source"topicを使うメタデータの取得

まず、先ほど"mdapi"topicで取得や生成した内容を削除しましょう。
image.png
image.png

次に、"source"topicのコマンドでmanifestを取得してみよう

sfdx force:source:retrieve -x manifest/package.xml 

-x 取得コンポーネントのmanifestを指定

image.png

無事にメタデータを取得したかを確認する

5-3.LWCを作成する

lightning web componentをCLIコマンドで作ってみよう

sfdx force:lightning:component:create -n newTreePlantation -d force-app/main/default/lwc/ --type=lwc

-n コンポーネントの名前
-d 出力するディレクトリ
--type lightning componentのタイプ

image.png
名前がnewTreePlantation、ディレクトリがforce-app/main/default/lwc/のlightning web componentを作成しました。

image.png
newTreePlantationの内容を以下に貼替ましょう。

newTreePlantation.html
<template>
    <lightning-card>
        <lightning-button slot="actions" label="Record New Plantation" variant="brand" onclick={recordNewPlantation}>
        </lightning-button>
        <template if:true={showForm}>
            <lightning-record-form object-api-name="Tree_Plantation__c" 
                    record-id={recordId} 
                    layout-type="Full" 
                    mode={mode}
                    onsuccess={handleSuccess}>
            </lightning-record-form>
        </template>
    </lightning-card>
</template>
newTreePlantation.js
import { LightningElement, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class NewTreePlantation extends LightningElement {

     recordId;
     showForm = false;

    recordNewPlantation(){
        this.showForm = true;
        this.recordId = undefined;
    }

    handleSuccess(event) {
        const evt = new ShowToastEvent({
            title: "Plantation Recorded",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(evt);
    }

    get mode(){
        return this.recordId ? 'view' : 'edit';
    }
}
newTreePlantation.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="newTreePlantation">
    <apiVersion>46.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

5-4"source"topicを使うメタデータのデプロイ

作成したLWCをCLIコマンドでデプロイしましょう。

 sfdx force:source:deploy --sourcepath force-app/main/default/lwc/

--sourcepath デプロイするソースのパス指定
image.png
image.png

組織にログインしLightning コンポーネントを検索してnewTreeplantationがデプロイ成功したかを確認

5-5."source"topicを使うメタデータの削除

"source"topicのCLIコマンドでメタデータを削除しましょう。

sfdx force:source:delete --sourcepath force-app/main/default/lwc/newTreePlantation/

ローカルファイルのnewTreePlantationが削除されたかを確認する。
image.png
組織の方が削除されているかを確認してみよう
image.png

5-6."mdapi"topicを使うメタデータのデプロイ

デプロイ用のmetadataフォルダを作成しよう
image.png
lwcの内容を入れよう

$ sfdx force:source:convert -r force-app/main/default/lwc -d metadata/

image.png
"mdapi"topicのCLIコマンドでデプロイしよう

sfdx force:mdapi:deploy -d metadata/

実行した後にデプロイが成功したかを確認してみよう、先ずはDeploy IDをコピーしよう
image.png

sfdx force:mdapi:deploy:report -i 君のDeploy ID

-i deployを確認するためのjob ID
image.png

無事にデプロイしました。
image.png

5-7.apexテストを一括に実行してみよう

CLIコマンドはapexテストすることができる

sfdx force:apex:test:run -l RunAllTestsInOrg -c -r=human

-l テストレベル
-c コードカバレッジ
-r 結果のタイプ

テスト結果
image.png

5-8.apexクラスを作成してみよう

CLIコマンドを使いapexクラスを生成してみよう

sfdx force:apex:class:create -n DemoclassTest -t=ApexUnitTest -d D:/sfdc/CLISession/force-app/main/default/classes

-n クラス名指定
-t テンプレートを決定
-d 生成したクラスの出力先

無事に生成しました。
image.png

6.CLIコマンド使うsalesforceデータの働き

CLIコマンドでbulk,enterprise,treeなどのAPIのほかデータベースのSOQLも操作することができます。

sfdx force:data --help

image.png

6-1.salesforce クエリデータの使うサーチCLIコマンド

ここで解説するのがsalesforce クエリデータを使うコマンドを解説します。先ずはサーチクエリでTreeクラスのIdとNameを検索してみよう。

sfdx force:data:soql:query --query="SELECT Id,Name FROM Tree__c" -r human

(git bashが使えない場合はpowershellなどに切替して試してください。)

検索した項目が表示されました。
image.png

6-2.salesforce クエリデータをCLIコマンドで生成、更新、削除する

まず、CLIコマンドで新しい項目のデータを生成しましょう。Tree NameがBingo TreeでBenefitがDummy Valueの項目を生成してみよう

sfdx force:data:record:create -s "Tree__c" --values "Name='Ringo Tree' Benefit__c='Dummy Value'"

-s 作成したいレコードの指定

新しいレコードを生成しました
image.png
次に、レコードの更新をCLIコマンドで実行してみてください。

sfdx force:data:record:update -s "Tree__c" -i "a0C2v000019p2NREAY" -v "Name='Ringo Jum'"

-s 作成したいレコードの指定
-i レコードのid指定
-v 数値の指定
image.png

更新した後のTreeクラスのレコードをもう一度調べよう、無事に変更しました
image.png

最後にCLIコマンドでレコードを削除してみよう。

sfdx force:data:record:delete -s "Tree__c" -i "a0C2v000019p2NREAY"

image.png

無事に削除しました。
image.png

6-4.Salesforceデータの出力

ここからはCLIコマンドでSalesforceデータのの出力を行います。まず、出力先のフォルダsample-dataを作成しましょう。
image.png
salesforce組織にログインしクイック検索欄にスキーマビルダーを検索しよう
image.png
スキーマビルダーに入り、選択解除をしましょう。
選択image.png
その後、今回出力するCity、Tree、Tree_Plantationだけを保存
image.png

まず、はTree、Tree_Plantationをjson書式で出力してみよう。

 sfdx force:data:tree:export --json --query="SELECT Id, Name, Picture__c,Benefit__c,(SELECT Id, Number_Of_Tree_Planted__c, Age__c, Tree__c, Planted_In__c FROM Tree_Plantation__r) FROM Tree__c " --plan --outputdir .\sample-data\

image.png
無事に出力出来ました
image.png
次に、Cityをjsonで出力してみよう。

sfdx force:data:tree:export --json --query="SELECT Id, Name, Location__latitude__s,Location__longitude__s,Target__c FROM City__c" --plan --outputdir sample-data/

無事に出力出来ました
image.png

6-5.Salesforceデータの入力

ここからはCLIコマンドでSalesforceデータの入力を行います。まず、planのJSONファイルにCity関連の内容を加えましょう。

Tree__c-Tree_Plantation__c-plan.json
[
    {
        "sobject": "Tree__c",
        "saveRefs": true,
        "resolveRefs": false,
        "files": [
            "Tree__cs.json"
        ]
    },
    {
        "sobject": "City__c",
        "saveRefs": true,
        "resolveRefs": false,
        "files": [
            "City__c.json"
        ]
    },
    {
        "sobject": "Tree_Plantation__c",
        "saveRefs": false,
        "resolveRefs": true,
        "files": [
            "Tree_Plantation__cs.json"
        ]
    }
  
]

次に、tree_PlantationにCityの関連項目を加えよう

Tree_Plantation__cs.json
{
    "records": [
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef1"
            },
            "Number_Of_Tree_Planted__c": 3000,
            "Age__c": 23,
            "Tree__c": "@Tree__cRef2",
            "Planted_In__c" : "@City__cRef1"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef2"
            },
            "Number_Of_Tree_Planted__c": 3000,
            "Age__c": 3,
            "Tree__c": "@Tree__cRef2",
            "Planted_In__c" : "@City__cRef2"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef3"
            },
            "Number_Of_Tree_Planted__c": 760,
            "Age__c": 2,
            "Tree__c": "@Tree__cRef2",
            "Planted_In__c" : "@City__cRef3"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef4"
            },
            "Number_Of_Tree_Planted__c": 3000,
            "Age__c": 3,
            "Tree__c": "@Tree__cRef2",
            "Planted_In__c" : "@City__cRef4"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef5"
            },
            "Number_Of_Tree_Planted__c": 600,
            "Age__c": 3,
            "Tree__c": "@Tree__cRef1",
            "Planted_In__c" : "@City__cRef1"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef6"
            },
            "Number_Of_Tree_Planted__c": 130,
            "Age__c": 2,
            "Tree__c": "@Tree__cRef3",
            "Planted_In__c" : "@City__cRef3"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef7"
            },
            "Number_Of_Tree_Planted__c": 180,
            "Age__c": 2,
            "Tree__c": "@Tree__cRef4",
            "Planted_In__c" : "@City__cRef4"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef8"
            },
            "Number_Of_Tree_Planted__c": 1080,
            "Age__c": 4,
            "Tree__c": "@Tree__cRef5",
            "Planted_In__c" : "@City__cRef5"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef9"
            },
            "Number_Of_Tree_Planted__c": 3000,
            "Age__c": 3,
            "Tree__c": "@Tree__cRef6",
            "Planted_In__c" : "@City__cRef3"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef10"
            },
            "Number_Of_Tree_Planted__c": 3000,
            "Age__c": 23,
            "Tree__c": "@Tree__cRef7",
            "Planted_In__c" : "@City__cRef2"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef11"
            },
            "Number_Of_Tree_Planted__c": 180,
            "Age__c": 2,
            "Tree__c": "@Tree__cRef8",
            "Planted_In__c" : "@City__cRef1"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef12"
            },
            "Number_Of_Tree_Planted__c": 1080,
            "Age__c": 4,
            "Tree__c": "@Tree__cRef8",
            "Planted_In__c" : "@City__cRef3"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef13"
            },
            "Number_Of_Tree_Planted__c": 760,
            "Age__c": 2,
            "Tree__c": "@Tree__cRef7",
            "Planted_In__c" : "@City__cRef4"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef14"
            },
            "Number_Of_Tree_Planted__c": 600,
            "Age__c": 3,
            "Tree__c": "@Tree__cRef6",
            "Planted_In__c" : "@City__cRef4"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef15"
            },
            "Number_Of_Tree_Planted__c": 3000,
            "Age__c": 3,
            "Tree__c": "@Tree__cRef5",
            "Planted_In__c" : "@City__cRef3"
        },
        {
            "attributes": {
                "type": "Tree_Plantation__c",
                "referenceId": "Tree_Plantation__cRef16"
            },
            "Number_Of_Tree_Planted__c": 130,
            "Age__c": 2,
            "Tree__c": "@Tree__cRef4",
            "Planted_In__c" : "@City__cRef2"
        }
    ]
}

最後にインポートしましょう。

 sfdx force:data:tree:import -p .\sample-data\Tree__c-Tree_Plantation__c-plan.json

7.スクラッチ組織の働きについて

ここからCLIコマンドでスクラッチ組織関連の一連の操作を行います。まず、salesforce組織にログインしDev Hubを有効化にしましょう。

image.png
Dev Hub組織にログインしましょう。

sfdx force:auth:web:login -d

image.png

7-1.スクラッチ組織の作成

CLIコマンドでスクラッチ組織を作成してみよう

sfdx force:org:create -a CLICourseSC1 -d 30 -f config/project-scratch-def.json -s 

-a 組織別名を付ける
-d 有効日数指定 
-f 組織定義のファイルパス指定
-s デフォルトユーザー名指定

スクラッチ組織を作成しました
image.png

\CLISession.sfdx\sfdx-config.jsonを開いてデフォルトユーザー名を変更したかを確認する
image.png

7-2.GitHubのリポジトリをスクラッチ組織にpush

Manish Choudhariさんのgithubに入り、tree-plantationのgit HTTPSをコピーしましょう。
https://github.com/choudharymanish8585/tree-plantation

image.png

sfdcフォルダにcloneしましょう
image.png

tree-plantationに入り組織にログインしてみよう。

cd tree-plantation\

sfdx force:auth:web:login -a CLISessionDevHub -d -s

push用スクラッチ組織を作成してみよう

sfdx force:org:create -a CLICourseSC1 -d 30 -f config/project-scratch-def.json -s

組織にpushしてみよう

sfdx force:source:push

image.png
アプリケーションマネージャーを確認しよう

sfdx force:org:open

image.png
権限を変更してアプリケーションランチャーに表示しよう

sfdx force:user:permset:assign -n TreePlantation

image.png

7-3.スクラッチ組織にデータをアップロードしよう

sample-dataの内容をアップロードしましょう。

sfdx force:data:tree:import -p .\sample-data\import-plan.json

image.png
アプリを開いて確認してみよう。
image.png
image.png

7-4.アプリを完成しよう

New Plantationタブを完成しよう
image.png
sfdcフォルダでNewTreePlantationのコンポーネントを作成しましょう。

 sfdx force:lightning:component:create -n newTreePlatation --type lwc -d force-app/main/default/lwc/

newTreePlantationフォルダの内容を入れ替えよ

newTreePlantation.html
<template>
    <lightning-card>
        <lightning-button slot="actions" label="Record New Plantation" variant="brand" onclick={recordNewPlantation}>
        </lightning-button>
        <template if:true={showForm}>
            <lightning-record-form object-api-name="Tree_Plantation__c" 
                    record-id={recordId} 
                    layout-type="Full" 
                    mode={mode}
                    onsuccess={handleSuccess}>
            </lightning-record-form>
        </template>
    </lightning-card>
</template>
newTreePlantation.js
import { LightningElement, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class NewTreePlantation extends LightningElement {

     recordId;
     showForm = false;

    recordNewPlantation(){
        this.showForm = true;
        this.recordId = undefined;
    }

    handleSuccess(event) {
        const evt = new ShowToastEvent({
            title: "Plantation Recorded",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(evt);
    }

    get mode(){
        return this.recordId ? 'view' : 'edit';
    }
}
newTreePlantation.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="newTreePlantation">
    <apiVersion>46.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

treePlantationExplorerフォルダの
組織のオブジェクトマネージャーを開いて、Treeを開く
image.png
項目とリレーションを選択してBenefit
image.png
項目レベルセキュリティの設定を選択する。
image.png
参照可能を選択する。
image.png
同じくTreeオブジェクトのtreeとCityオブジェクトのLocation、Tree PlantationオブジェクトのPlanted_In、Treeの項目レベルセキュリティを設定する

もう一度pushしましょう。

sfdx force:source:push

tree plantationをもう一度確認する
image.png
ボタンをクリックしましょう
image.png

完成したアプリをテストしましょう。

sfdx force:apex:test:run --testlevel RunAllTestsInOrg --codecoverage --resultformat human

image.png

8.開発ソースの流れ

ここではgithubなどバージョン管理ツールを用いて一通り開発の流れを紹介します。

8-1.ソース開発の流れ一覧

github上にDev、QA、UAT、MASTERなどのブランチを作成する。開発用のがDevブランチ、QAがグループ内のテスト用で、UATは検収テスト、MASTERは本番アップロード用
image.png

8-2.ソースの変更管理とスクラッチ組織へソースのpushとpull

現在開発中プロジェクトの変更を調べるにはこのCLIコマンドで調べる

force:source:status

ローカルの変更を調べるCLIコマンド

force:source:status -l

ここからはスクラッチ組織でTreePlantationの権限変更を行う、検索欄に権限を入力して権限セットを選択してTreePlantationを開く。
image.png
権限セットのオブジェクト設定を開く
image.png
TreePlantationのオブジェクト設定を開く
image.png
編集をクリックして作成権限を取り消して保存しましょう。
image.png

image.png
変更した後にリモートの変更を調べるCLIコマンド

sfdx force:source:status -r

スクラッチ組織権限の変更が確認取れる
image.png
ローカルの権限設定を確認しましょう。tree-plantation\force-app\main\default\permissionsets\

TreePlantation.permissionset-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
    <applicationVisibilities>
        <application>Tree_Plantation</application>
        <visible>true</visible>
    </applicationVisibilities>
    <fieldPermissions>
        <editable>true</editable>
        <field>City__c.Location__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>true</editable>
        <field>City__c.Target__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>true</editable>
        <field>Tree_Plantation__c.Age__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>true</editable>
        <field>Tree_Plantation__c.Number_Of_Tree_Planted__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>true</editable>
        <field>Tree__c.Benefit__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <fieldPermissions>
        <editable>true</editable>
        <field>Tree__c.Picture__c</field>
        <readable>true</readable>
    </fieldPermissions>
    <hasActivationRequired>false</hasActivationRequired>
    <label>TreePlantation</label>
    <objectPermissions>
        <allowCreate>true</allowCreate>
        <allowDelete>true</allowDelete>
        <allowEdit>true</allowEdit>
        <allowRead>true</allowRead>
        <modifyAllRecords>false</modifyAllRecords>
        <object>City__c</object>
        <viewAllRecords>false</viewAllRecords>
    </objectPermissions>
    <objectPermissions>
        <allowCreate>true</allowCreate>
        <allowDelete>true</allowDelete>
        <allowEdit>true</allowEdit>
        <allowRead>true</allowRead>
        <modifyAllRecords>false</modifyAllRecords>
        <object>Tree_Plantation__c</object>
        <viewAllRecords>false</viewAllRecords>
    </objectPermissions>
    <objectPermissions>
        <allowCreate>true</allowCreate>
        <allowDelete>true</allowDelete>
        <allowEdit>true</allowEdit>
        <allowRead>true</allowRead>
        <modifyAllRecords>false</modifyAllRecords>
        <object>Tree__c</object>
        <viewAllRecords>false</viewAllRecords>
    </objectPermissions>
    <tabSettings>
        <tab>City__c</tab>
        <visibility>Visible</visibility>
    </tabSettings>
    <tabSettings>
        <tab>Tree_Plantation</tab>
        <visibility>Visible</visibility>
    </tabSettings>
    <tabSettings>
        <tab>Tree_Plantation__c</tab>
        <visibility>Visible</visibility>
    </tabSettings>
    <tabSettings>
        <tab>Tree__c</tab>
        <visibility>Visible</visibility>
    </tabSettings>
</PermissionSet>

TreePlantationのオブジェクト権限が変更前の状態である

 <objectPermissions>
        <allowCreate>true</allowCreate>
        <allowDelete>true</allowDelete>
        <allowEdit>true</allowEdit>
        <allowRead>true</allowRead>
        <modifyAllRecords>false</modifyAllRecords>
        <object>Tree_Plantation__c</object>
        <viewAllRecords>false</viewAllRecords>
    </objectPermissions>

スクラッチ組織のメタデータをCLIコマンドでpullしてみよう。

sfdx force:source:pull

ローカルのTreePlantationの権限設定がスクラッチ組織方と同じになりました
image.png
ローカルのTreePlantationの権限設定を変更してpushしましょう。
image.png

sfdx force:source:push

無事に変更しました
image.png

9.Cliコマンドの自動化

ここではCLIコマンドの自動化を実現する

9-1.SSL証明書を作成しましょう

まず、SFDCフォルダにassetsフォルダを作成しましょう。
image.png
次に、サーバーパスキーを作成しましょう

openssl genrsa -passout pass:x -out server.pass.key 2048

image.png
更に、サーバーキーを作成しましょう

openssl rsa -passin pass:x -in server.pass.key -out server.key

image.png
そして、に証明書を作成しましょう,パスワードの入力なしで

 openssl req -new -key server.key -out server.csr

image.png
最後に証明書を作成しましょう

openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

image.png

9-2.接続アプリを作成

まず、アプリケーションマネージャーを検索し新規接続アプリケーションをクリックしましょう。
image.png
次に、新規接続アプリの基本情報の接続アプリケーション名、API 参照名、取引先責任者 メールを選択する。
image.png
更に、API (OAuth 設定の有効化)、デジタル署名を使用、Web サーバフローの秘密が必要、更新トークンフローの秘密が必要に全部チェック入れよう、コールバック URLにhttp://localhost:1717/OauthRedirect と入力して、選択ファイルはserver.ctr
image.png
決定ボタンを押しましょう、次へ
image.png

作成完了したらManageを押しましょう
image.png
ポリシーを編集を押しましょう
image.png
承認されたユーザーを変更しましょう。
image.png
プロファイルを管理するをクリック
image.png
システム管理者をチェック
image.png

証明書とキーを使いアプリに接続しましょう。

sfdx force:auth:jwt:grant --clientid <コンシューマ鍵> --jwtkeyfile  <サーバーキーの位置> --username <ユーザー名> --setdefaultdevhubusername

image.png

9-3.CLI自動化

ここではshファイルを使い、CLIコマンドの自動化を実現する

cli-session-automation.sh
# Set env/temp variable
printf "STEP 1: Setting up temp variable\n"
export DEV_HUB_USER_NAME=hu01@bin.com
export COSUMER_KEY=3MVG9wt4IL4O5wvK9Ej2ruY3EJIRfqLRu_YbEVMEUC4eAIxYa9exg067gxE1t78KtcaJUVHyOzDXreHVz_NBL
export SERVER_KEY_LOCATION="D:/sfdc/assets/server.key"
export SFDX_PROJECT_LOCATION="D:/sfdc"


printf "STEP 2: Moving in project folder $SFDX_PROJECT_LOCATION\n"
cd $SFDX_PROJECT_LOCATION

printf "STEP 3: Creating new directory $(date +'%Y%m%d')\n"
mkdir $(date +'%Y%m%d')
cd $(date +'%Y%m%d')

# cloning github repo
printf "STEP 4: Cloning github repo\n"
git clone https://github.com/MynameIsUseful/tree-plantation.git
cd tree-plantation

image.png
この記事で行ったその他操作も加えよう

cli-session-automation.sh
# Set env/temp variable
printf "STEP 1: Setting up temp variable\n"
export DEV_HUB_USER_NAME=hu01@bin.com
export COSUMER_KEY=3MVG9wt4IL4O5wvK9Ej2ruY3EJIRfqLRu_YbEVMEUC4eAIxYa9exg067gxE1t78KtcaJUVHyOzDXreHVz_NBL
export SERVER_KEY_LOCATION="D:/sfdc/assets/server.key"
export SFDX_PROJECT_LOCATION="D:/sfdc"


printf "STEP 2: Moving in project folder $SFDX_PROJECT_LOCATION\n"
cd $SFDX_PROJECT_LOCATION

printf "STEP 3: Creating new directory $(date +'%Y%m%d')\n"
mkdir $(date +'%Y%m%d')
cd $(date +'%Y%m%d')

# cloning github repo
printf "STEP 4: Cloning github repo\n"
git clone https://github.com/choudharymanish8585/tree-plantation.git
cd tree-plantation

# authorize dev hub org
printf "STEP 5: Authorizing Dev Hub Org\n"
sfdx force:auth:jwt:grant --clientid $COSUMER_KEY --jwtkeyfile  "$SERVER_KEY_LOCATION" --username $DEV_HUB_USER_NAME --setdefaultdevhubusername --setalias CLISessionDevHub

# creating scratch org
printf "STEP 6: Creating scratch org\n"
 sfdx force:org:create  --setdefaultusername --definitionfile config/project-scratch-def.json --setalias $(date +'%Y%m%d') --wait 10 --durationdays 30

# pushing metadata to scracth org
printf "STEP 7: Pushing metadata to scratch org"
sfdx force:source:push

# assign permission set
printf "STEP 8: Assigning permission set"
sfdx force:user:permset:assign -n TreePlantation

# upload sample data to scratch org
printf "STEP 9: Uploading sample data"
sfdx force:data:tree:import --plan sample-data/import-plan.json

# opening scratch org
printf "STEP 10: Opening scratch org"
sfdx force:org:open

8.CLIコマンドの自動化のまとめ

この記事ではCLIコマンドの自動化を行うための環境準備、salesforce組織権限設定、よく使うCLIコマンドや開発の流れなどを紹介しました。
接続アプリケーションを作成し証明書を選択して一連のコマンドをshに書き込み自動的にアップロードや変更が実現可能になりました。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6