技術メモ(主に自分向け)

短期記憶の自分向けの技術メモです。

API名で連番になっている項目に順番に値を設定する方法

以下のような項目が存在し、順番に値を入れたい場合、for文で順番に入れることが可能

・test1__c
・test2__c
・test3__c


以下のように書く。

TestObject__c to = new TestObject((Id = 'xxx'));
List<String> srtList = new List<String>['A', 'B', 'C'];
for (Integer i = 0; i <) {
 to.put('test' + (i + 1) + '__c', strList.get(i));
}

これで以下のような値がそれぞれに入る

・test1__c:A
・test2__c:B
・test3__c:C

ランダムでレコードを抽出する方法

ランダムでレコードを抽出する方法は以下の通り。
【やりたいこと/前提条件】
 ・5レコード抽出
 ・重複なし
 ・オブジェクト:testObject
 ・項目に一意の数字(Index__c)を保持
 ・insertTestはWrapperクラス。Stirng型のNameとInsertIndexという変数を持っていて、抽出したレコードを格納する。

List<insertTest> insertTestList = new List<insertTest>();
List<testObject__c> toList = [SELECT 
               Id,
               Name,
               Index__c
             From
               testObject];

for (Integer i = 0, insertTestList .size() < 5; i++) {
 insertTest it = new insertTest();
 Integer rand = Math.round(Math.random() * (toList.size() - 1));
 String strIndex = toList[rand].Index__c;
 Boolean checkFlag = false;

 //ランダムで抽出したレコードが既にリストに入っていないか確認
 for (Integer j = 0; j < insertTestList.size(); j++) {
  if (insertTestList [j].InsertIndex.equales(strIndex)) {
   checkFlag = true;
   break;  
  }
  else {
   checkFlag = false;
  }
 }
 //ランダムで抽出したレコードを抽出用リストに格納
 if (!checkFlag) {
  insertTest.Name = toList[rand].Name;
  insertTest.InsertIndex = toList[rand].index__c;
 }
}

・Wrapperクラス

public class insertTest {
 @AuraEnabled public String Name {get; set;};
 @AuraEnabled public String InsertIndex {get; set;};

 public insertTest() {
  Name = '';
  InsertIndex = '';
 } 
}

非同期処理の書き方

非同期処理を行うメソッドには「@future」をメソッドの上につける。
Userのような設定オブジェクトでは、
適切なアクセスレベル権限で操作が実行されるため、
別のトランザクションで挿入/更新をする必要がある。

エラー例:MIXED_DML_OPERATION, 非設定オブジェクトを更新した後の設定オブジェクト上のDML操作(またはその逆)は、許可されていません

ハッシュ値と暗号化の書き方

Apexクラスでハッシュ値の作成と暗号化の書き方をメモ。
(もしかしたら他に良い書き方があるかもですが、、、参考程度に)

Integer intToken = 99; //tokenの文字列を100文字と設定
Integer position;
String charList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; //ハッシュ値に使用する文字列
String strHash = '';

//ハッシュ値作成
for (Integer i = 0; i <= intToken; i++) {
 position = Integer.valueof(String.valueof(Math.roundToLong(charList.length() * Math.random))) - 1;
 if (position < 0) position = 0;
 strHash += charList.substring(position, poosition + 1);
}

//暗号化
if (!String.isBlank(strHash)) {
 EncodingUtil.convertToHex(Crypto.generateDigest('H-256', Blob.valueOf(strHash))):
}

EncodingUtil.base64Encode(hash)の場合、桁落ちする可能性があるため
EncodingUtil.convertToHexをかませて16新文字列にしています。

選択肢をランダムに表示

とある問いに対して選択肢が複数ある場合、ページを開くたびに選択肢の並び順をランダムにする方法
js側
※問題、選択肢はリストで保持しているとする

//問題数分実行する
for (var questionList = 0; questionList < 問題.length; questionList++) {
 //選択肢の並び順をランダムで設定
 for (var i = 問題[questionList].選択肢.length -1; i >= 0; i--) {
  var randomNumber = Math.floor(Math.random() * (i + 1));
  [問題[questionList].選択肢[i], 問題[questionList].選択肢[randomNumber]] = [問題[questionList].選択肢[randomNumber], 問題[questionList].選択肢[i]];
 }
}