Apexメソッドにレコード情報をJSONで受け渡すサンプル

環境
salesforce

操作方法
1.LWC側のJavaScriptコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import { LightningElement } from 'lwc';
import createAccount from '@salesforce/apex/TestClass.createAccount';
export default class Sample extends LightningElement {
createdAccountId;
handleSubmit(){
const recordInput = {
"Name": "Yamada",
"Industry": "Biotechnology",
"NumberOfEmployees": 100,
}
createAccount({recordInfoJson: JSON.stringify(recordInput)})
.then(createdRecord => {
this.createdAccountId = createdRecord.Id;
});
}
}
import { LightningElement } from 'lwc'; import createAccount from '@salesforce/apex/TestClass.createAccount'; export default class Sample extends LightningElement { createdAccountId; handleSubmit(){ const recordInput = { "Name": "Yamada", "Industry": "Biotechnology", "NumberOfEmployees": 100, } createAccount({recordInfoJson: JSON.stringify(recordInput)}) .then(createdRecord => { this.createdAccountId = createdRecord.Id; }); } }
import { LightningElement } from 'lwc';
import createAccount from '@salesforce/apex/TestClass.createAccount';

export default class Sample extends LightningElement {
    createdAccountId;

    handleSubmit(){
        const recordInput = {
            "Name": "Yamada",
            "Industry": "Biotechnology",
            "NumberOfEmployees": 100,
        }
        createAccount({recordInfoJson: JSON.stringify(recordInput)})
        .then(createdRecord => {
            this.createdAccountId = createdRecord.Id;
        });
    }
}

説明
JSON.stringify() で JSON化してApexクラスのメソッドに引数として渡します。

2.Apexメソッド側の処理コード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public with sharing class TestClass {
@AuraEnabled
public static Account createAccount(String recordInfoJson){
try {
Account acct = (Account)JSON.deserialize(recordInfoJson, Account.class);
insert acct;
return acct;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
}
public with sharing class TestClass { @AuraEnabled public static Account createAccount(String recordInfoJson){ try { Account acct = (Account)JSON.deserialize(recordInfoJson, Account.class); insert acct; return acct; } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } } }
public with sharing class TestClass {
    @AuraEnabled
    public static Account createAccount(String recordInfoJson){
        try {
            Account acct = (Account)JSON.deserialize(recordInfoJson, Account.class);
            insert acct;
            return acct;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

説明
String として受け取り、JSON.deserialize() で各オブジェクト型に変換します。

Apex

Posted by arkgame