Salesforce Snippets
A VS Code Extension with Apex and LWC Snippets.
List of Snippets
Extension contains 146 code snippets.
Apex
LWC
Apex example
LWC JS example
LWC HTML example
Features
Prefix |
Example |
AccessLevelSystemMode |
AccessLevel.SYSTEM_MODE
|
AccessLevelUserMode |
AccessLevel.USER_MODE
|
Prefix |
Example |
AccessTypeCreatable |
AccessType.CREATABLE
|
AccessTypeReadable |
AccessType.READABLE
|
AccessTypeUpdatable |
AccessType.UPDATABLE
|
AccessTypeUpsertable |
AccessType.UPSERTABLE
|
Prefix |
Example |
assertAreEqual, Assert.areEqual, aae |
Assert.areEqual(1, 2, 'NOT EQUAL');
|
assertAreNotEqual, Assert.areNotEqual, aane |
Assert.areNotEqual(1, 1, 'Your custom message here');
|
assertFail, Assert.fail, af |
Assert.fail('Your custom message here');
|
assertIsFalse, Assert.isFalse, aif |
Assert.isFalse(true, 'Your custom message here');
|
assertIsInstanceOfType, Assert.isInstanceOfType, aii |
Assert.isInstanceOfType(new Account(), Contact.class, 'Your custom message here');
|
assertIsNotInstanceOfType, Assert.isNotInstanceOfType, aini |
Assert.isNotInstanceOfType(new Account(), Account.class, 'Your custom message here');
|
assertIsNotNull, Assert.isNotNull, ainn |
Assert.isNotNull(null, 'Your message here');
|
assertIsNull, Assert.isNull, ain |
Assert.isNull(null, 'Your message here');
|
assertIsTrue, Assert.isTrue, ait |
Assert.isTrue(null, 'Your message here');
|
Prefix |
Example |
Database.countQuery |
Integer recordsAmount = Database.countQuery(queryString);
|
Database.delete |
List<Database.DeleteResult> deleteResults = Database.delete(recordsToDelete, allOrNone);
|
Database.executeBatch, deb |
Id jobId = Database.executeBatch(new BatchLeadConvert(), 200);
|
Database.insert |
List<Database.SaveResult> saveResults = Database.insert(recordsToInsert, allOrNone);
|
Database.update |
List<Database.SaveResult> updateResults = Database.update(recordsToUpdate, allOrNone);
|
Prefix |
Example |
JSON.deserialize |
ApexType result = (ApexType) JSON.deserialize(jsonString, ApexType.class);
|
JSON.deserializeStrict |
ApexType result = (ApexType) JSON.deserializeStrict(jsonString, ApexType.class);
|
JSON.serialize |
String serializedResult = JSON.serialize(objectToSerialize);
|
JSON.serializePretty |
String serializedResult = JSON.serializePretty(objectToSerialize);
|
Prefix |
Example |
String.escapeSingleQuotes |
String result = String.escapeSingleQuotes(stringToEscape);
|
String.format |
String template = '{0} was last updated {1}';
List<Object> parameters = new List<Object>{ 'Universal Containers', DateTime.newInstance(2018, 11, 15) };
String formatted = String.format(template, parameters);
|
String.isBlank |
String.isBlank(inputString)
|
String.isNotBlank |
String.isNotBlank(inputString)
|
String.isNotEmpty |
String.isNotEmpty(inputString)
|
String.join |
String result = String.join(iterableObj, 'separator');
|
String.valueOf |
String result = String.valueOf(valueToConvert);
|
Prefix |
Example |
Test.calculatePermissionSetGroup |
Test.calculatePermissionSetGroup(permissionSetGroupId);
|
Test.calculatePermissionSetGroups |
Test.calculatePermissionSetGroup(listOfPermissionSetGroupsIds);
|
Test.clearApexPageMessages |
Test.clearApexPageMessages();
|
Test.enableChangeDataCapture |
Test.enableChangeDataCapture();
|
Test.getEventBus |
Test.getEventBus().deliver();
|
Test.getStandardPricebookId |
Id pricebookId = Test.getStandardPricebookId();
|
Test.isRunningTest |
Test.isRunningTest()
|
Test.loadData |
List<SObject> records = Test.loadData(ObjectApiName.SObjectType, 'staticResourceName');
|
Test.setCurrentPage |
Test.setCurrentPage(pageReference);
|
Test.setMock |
Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImplementation());
|
Test.startTest |
Test.startTest();
|
Test.stopTest |
Test.stopTest();
|
Prefix |
Example |
UserInfogetDefaultCurrency |
UserInfo.getDefaultCurrency();
|
UserInfogetFirstName |
UserInfo.getFirstName();
|
UserInfogetLanguage |
UserInfo.getLanguage();
|
UserInfogetLastName |
UserInfo.getLastName();
|
UserInfogetName |
UserInfo.getName();
|
UserInfogetProfileId |
UserInfo.getProfileId();
|
UserInfogetUserEmail |
UserInfo.getUserEmail();
|
UserInfogetUserId |
UserInfo.getUserId();
|
UserInfogetUserType |
UserInfo.getUserType();
|
Others
Prefix |
Example |
forSoql, foro |
for (Type variable : [SELECT fieldsList FROM Type) {
//Your code here
}
|
fori, itar |
for (Integer i = 0; i < listName.size(); i++) {
Account acc = listName[i];
// Your code here
}
|
forMap, itme |
for (Id accountId : mapName.keySet()) {
Account acc = mapName.get(accountId);
//Your code here
}
|
forReversedOrder, ritar |
for (Integer i = listName.size()-1; i >= 0; i--) {
Account acc = listName[i];
//Your code here
}
|
future |
@future
public static void methodName() {
//Your code here
}
|
if |
if (true) {
//Your code here
}
|
ifElse, ife |
if(true) {
//Your code here
} else {
}
|
instanceOf, inst |
if (objects[0] instanceof Account) {
Account acc = (Account) objects[0];
}
|
invocableMethod |
@InvocableMethod(label='YourLabeL' description='Description' category='Category')
public static List<Account> exampleMethod() {
//Your code here
}
|
isAssignableFrom |
ChildType.class.isAssignableFrom(SourceType.class);
|
lastListElement, lst |
myList[myList.size() - 1]
|
lazy |
if (myAccount == null) {
myAccount = new Account();
}
|
list, nl |
List<Account> testAccounts = new List<Account>();
|
map, nm |
Map<Id, Account> testAccounts = new Map<Id, Account>();
|
set, ns |
Set<Id> accountIds = new Set<Id>();
|
setOfIds, nsfl |
Set<Id> accountIds = new Map<Id, Account>([SELECT Id FROM Account LIMIT 10]).keySet();
|
mapFromList, nmfl |
Map<Id, Account> myAccounts = new Map<Id, Account>(accountsList);
|
pro |
{get; private set;}
|
prw |
{get; set;}
|
final, psf |
public static final
|
finalInteger, psfi |
public static final Integer
|
finalString, psfs |
public static final String
|
select, SEL |
SELECT Id FROM Account
|
selectAll, SELALL |
SELECT FIELDS(ALL) FROM Account LIMIT 200
|
selectToMap, sqm |
Map<Id, Account> myAccounts = new Map<Id, Account>([SELECT Id FROM Account LIMIT 10]);
|
selectToList, sql |
List<Account> myAccounts = [SELECT Id, Name FROM Account];
|
selectToObject, sql1 |
List<Account> myAccounts = [SELECT Id FROM Account LIMIT 1];
Account myAcc = myAccounts.size() == 1 ? myAccounts.get(0) : null;
|
systemAssert, sa |
System.assert(condition, 'Your message here');
|
systemAssertEquals, sae |
System.assertEquals(expected, actual, 'Your message here');
|
systemAssertEquals, san |
System.assertEquals(null, actual, 'Your message here');
|
systemAssertFail, saf |
System.assert(false, 'Your message here');
|
systemAssertNotEquals, sane |
System.assertNotEquals(expected, actual, 'Your message here');
|
systemAssertNotEquals, sann |
System.assertNotEquals(null, 'Your message here');
|
systemDebug, sd |
System.debug(LoggingLevel.DEBUG, 'your message here: ' + variableHere);
|
systemDebugPretty, sdp |
System.debug(LoggingLevel.DEBUG, 'your message here: ' + JSON.SerializePretty(objectVariable));
|
systemRunAs, sra |
System.runAs(user) {
//your code here
}
|
isTest, tstm |
@IsTest
static void exampleName() {
//Your code here
Test.startTest();
Test.stopTest();
}
|
testSetup, tsts |
@TestSetup
static void setup() {
//Your code here
}
|
throw, thr |
throw new CustomException();
|
tryCatch, tc |
try {
//Your code here
} catch (CustomException ex) {
}
|
tryCatchFinally, tcf |
try {
//Your code here
} catch (CustomException ex) {
} finally {
}
|
while, wh |
while (condition) {
//Your code here
}
|
LWC
Prefix |
Example |
lightning-button |
<lightning-button variant='base' label='label' title='title' onclick={handleOnClick} class='cssClass'>
</lightning-button>
|
lightning-combobox |
<lightning-combobox
name='name'
label='label'
value={value}
placeholder='placeholder'
options={options}
onchange={handleChange}
></lightning-combobox>
|
lightning-datatable |
<lightning-datatable
key-field='Id'
data={data}
columns={columns}
hide-checkbox-column
></lightning-datatable>
|
lightning-icon |
<lightning-icon icon-name='iconName' alternative-text='alternativeText' title='title'>
</lightning-icon>
|
lightning-input |
<lightning-input type='type' label='label' onchange='handleOnChange'>
</lightning-input>
|
lightning-input-field |
<lightning-input-field field-name='fieldName' disabled read-only required>
</lightning-input-field>
|
lightning-layout |
<lightning-layout horizontal-align='horiznotalAlign' vertical-align='verticalAlign' multiple-rows='multipleRows'>
<lightning-layout-item padding='around-small'>
</lightning-layout-item>
<lightning-layout-item padding='around-small'>
</lightning-layout-item>
<lightning-layout-item padding='around-small'>
</lightning-layout-item>
</lightning-layout>
|
lightning-layout-item |
<lightning-layout-item size='size' small-device-size='smallDeviceSize' medium-device-size='mediumDeviceSize' large-device-size='largeDeviceSize' padding='around-small'>
</lightning-layout-item>
|
lightning-tabset |
<lightning-tabset variant='variant' active-tab-value='two'>
<lightning-tab label='Item One' value='one'>
One Content !
</lightning-tab>
<lightning-tab label='Item Two' value='two'>
Two Content !
</lightning-tab>
<lightning-tab label='Item Three' value='three'>
Three Content !
</lightning-tab>
</lightning-tabset>
|
lightning-tabset |
<lightning-spinner alternative-text='alternativeText' size='size'>
</lightning-spinner>
|
slot |
<slot name='name'>
</slot>
|
templateForEach |
<template for:each={array} for:item='item'>
</template>
|
templateIfFalse |
<template if:false={property}>
</template>
|
templateIfTrue |
<template if:true={property}>
</template>
|
templateIteratorIt |
<template iterator:it={array}>
<div key={it.value.Id}>
<div if:true={it.first}></div>
{it.value.Name}
<div if:true={it.last}></div>
</div>
</template>
|
Prefix |
Example |
asyncAwait |
try {
const result = await apexMethodName({ apexMethodParams });
} catch (error) {
console.error(error)
}
|
constructor |
constructor() {
}
|
currentPageReference |
import { CurrentPageReference } from 'lightning/navigation';
@wire(CurrentPageReference)
pageRef;
|
customEvent |
new CustomEvent('eventName', {
detail: details,
bubbles: false,
composed: false
});
|
disconnectedCallback |
disconnectedCallback() {
}
|
dispatchEvent |
this.dispatchEvent(customEvent);
|
errorCallback |
errorCallback(error, stack) {
}
|
forEach |
array.forEach((item, index) => {
});
|
getObjectInfo |
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import objectName from '@salesforce/schema/objectApiName';
@wire(getObjectInfo, { objectApiName: objectName })
propertyOrFunction;
|
getPicklistValues |
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import fieldName from '@salesforce/schema/objectApiName.fieldApiName';
@wire(getPicklistValues, { recordTypeId: '012000000000000AAA', fieldApiName: fieldName })
propertyOrFunction;
|
getRecord |
import { getRecord } from 'lightning/uiRecordApi';
@wire(getRecord, { recordId: 'recordId', fields: fields })
propertyOrFunction;
|
getRecords |
import { getRecords } from 'lightning/uiRecordApi';
@wire(getRecords, { records: [ { recordIds: 'recordIds', fields: fields } ] })
propertyOrFunction;
|
importApexMethod |
import apexMethodName from '@salesforce/apex/Namespace.ClassName.apexMethodReference';
|
importField |
import fieldName from '@salesforce/schema/objectApiName.fieldApiName';
|
importHasPermission |
import hasPermissionName from '@salesforce/userPermission/PermissionName';
|
importNavigationMixin |
import { NavigationMixin } from 'lightning/navigation';
|
importObject |
import objectName from '@salesforce/schema/objectApiName';
|
importUserId |
import userId from '@salesforce/user/Id';
|
map |
array.map((item, index) => {
return {
}
});
|
importMessageChannel |
import channelName from '@salesforce/messageChannel/channelReference';
|
navigate |
this[NavigationMixin.Navigate](https://github.com/beyond-the-cloud-dev/vsc-salesforce-code-snippets/blob/HEAD/{
type: 'standard__app',
attributes: {
/ Different per page type.
/ Check documentation: https:/developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reference_page_reference_type
},
state: {
/ Different per page type.
}
});
|
querySelector |
this.template.querySelector('element');
|
querySelectorAll |
this.template.querySelectorAll('element');
|
importRefreshApex |
import { refreshApex } from '@salesforce/apex';
|
render |
render() {
}
|
renderedCallback |
initialRender = true;
renderedCallback() {
if (!this.initialRender) {
return;
}
// Your code here.
this.initialRender = false;
}
|
showToastEvent |
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
new ShowToastEvent({ 'title', 'message', 'variant' });
|
importStaticResource |
import resourceName from '@salesforce/resourceUrl/resourceName';
|
thenCatch |
apexMethodName({ apexMethodParams })
.then(result => {
})
.catch(error => {
console.error(error)
});
|
wireMethod |
@wire(apexMethodName, { apexMethodParams })
wiredName({ error, data }) {
if (data) {
} else if (error) {
console.error(error);
}
}
|
wireProperty |
@wire(apexMethodName, { apexMethodParams })
property;
|
Prefix |
Example |
capability |
<capability>lightningCommunity__RelaxedCSP</capability>
<capability>lightning__ServiceCloudVoiceToolkitApi</capability>
|
isExposed |
<isExposed>true</isExposed>
|
masterLabel |
<masterLabel>titleOfTheComponent</masterLabel>
|
targets |
<targets>
<target>lightning__AppPage</target>
</targets>
|
targetConfig |
<targetConfig targets="lightningCommunity__Page">
<propertyType
name="copied from clipboard"
label="label"
type|extension="type"
default="default"
description="description"
/>
</targetConfig>
|
propertyType |
<propertyType
name="copied from clipboard"
label="label"
type|extension="type"
default="default"
description="description"
/>
|
| |