Notes
ArrayMethodsDemo.html
<template>
<lightning-card title="Create Account">
<div class="slds-p-around_medium">
<lightning-input label="Account Name" value={accountRecord.Name} onchange={handleChange} data-field="Name"></lightning-input>
<lightning-input label="Industry" value={accountRecord.Industry} onchange={handleChange} data-field="Industry"></lightning-input>
<lightning-input label="Phone" value={accountRecord.Phone} onchange={handleChange} data-field="Phone"></lightning-input>
<lightning-button label="Create Account" onclick={handleCreate} variant="brand" class="slds-m-top_medium"></lightning-button>
</div>
<p if:true={message} class="slds-p-around_medium">{message}</p>
</lightning-card>
</template>
ArrayMethodsDemo.js
import { LightningElement, track } from 'lwc';
import createAccount from '@salesforce/apex/AccountController.createAccount';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CreateAccountForm extends LightningElement {
@track accountRecord = {
Name: '',
Industry: '',
Phone: ''
};
@track message = '';
handleChange(event) {
const field = event.target.dataset.field;
this.accountRecord[field] = event.target.value;
}
handleCreate() {
const accountJson = JSON.stringify(this.accountRecord);
createAccount({ accountJson }) // Send as JSON
.then(result => {
this.message = result;
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: result,
variant: 'success'
})
);
})
.catch(error => {
this.message = 'Error: ' + error.body.message;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: error.body.message,
variant: 'error'
})
);
});
}
}
APEX
public with sharing class AccountController {
@AuraEnabled
public static String createAccount(String accountJson) {
try {
Account acc = (Account) JSON.deserialize(accountJson, Account.class);
insert acc;
return 'Account created successfully with ID: ' + acc.Id;
} catch (Exception e) {
throw new AuraHandledException('Error: ' + e.getMessage());
}
}
}
Meta XML
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="createAccountForm">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>