Skip to content
| Marketplace
Sign in
Visual Studio Code>Snippets>Salesforce SnippetsNew to Visual Studio Code? Get it now.

Salesforce Snippets

Beyond The Cloud

beyondthecloud.dev
|
1,664 installs
| (7) | Free
Snippets for Salesforce Apex and LWC
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Salesforce Snippets

A VS Code Extension with Apex and LWC Snippets.

Visual Studio Marketplace Installs Stars LastCommit

List of Snippets

Extension contains 119 code snippets.

Apex LWC-HTML LWC-JS LWC-XML

Apex example




LWC JS example




LWC HTML example

Features

Apex

Assert Class

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');

Database Class

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);

JSON Class

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);

String Class

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);

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

HTML

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>

JS

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;

XML

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"
/>
  • Contact us
  • Jobs
  • Privacy
  • Terms of use
  • Trademarks
© 2023 Microsoft