Wednesday, January 9, 2019

Apex snippets in Visual Studio Code

This post explains about how to add apex user snippets and how to use snippets in visual studio code

snippets are templates that make it easier to enter repeating code patterns, such as loops or conditional statements.

How to create snippets

Path: File > Preferences > user snippets
then select your language.json file

then enter your snippets in JSON file 

Ex: 
"List_Apex": {
 "prefix": "list<",
 "body": [
  "list<${1:object}> ${2:lstName} = new list<${1}>();"
 ],
 "description":"List of sObjects"
},
List_Apex: is the snippet name, you can enter your snippet name
prefix: defines how this snippet is selected from IntelliSense and tab completion.
body: is the content and either a single string or an array of strings of which each element will be inserted as a separate line.
description: description of your snippet(it is optional).

The example above has two placeholders, ${1:object} and ${2:lstName}. You can quickly traverse them in the order of their number. The string after the number and colon is used as an initial default.

you can make the editor cursor move inside a snippet. Use $1, $2 to specify cursor locations. The number is the order in which tabstops will be visited, whereas $0 denotes the final cursor position.
$1 indicates the first tab stop.

Examples

I created few snippets in the apex, 
{
 //For  List
"List_Apex": {
 "prefix": "list<",
 "body": [
  "list<${1:object}> ${2:lstName} = new list<${1}>();"
 ],
 "description":"List of sObjects"
},

// for set
"Set_Apex": {
 "prefix": "set<",
 "body": [
  "set<${1:object}> ${2:setName} = new set<${1}>();"
 ],
 "description":"Set of sObjects"
},

// for map
"Map_Apex": {
 "prefix": "map<",
 "body": [
  "map<${1:object}, ${2:object}> ${3:mapName} = new map<${1}, ${2}>();"
 ],
 "description":"Map of sObjects"
},

// for each loop
"For_Loop_Apex": {
 "prefix": "for",
 "body": [
  "for (${2:element} ${3:iteratorName} : ${1:array}) {",
  "\t$0",
  "}"
 ],
 "description": "For Loop"
},

// if condition
"if_cond_Apex": {
 "prefix": "if",
 "body": ["if ($1) {\n    $0\n}"],
 "description": "if statement for apex"
  },
 
 // soql apex
"soql_Apex": {
 "prefix": "soql",
 "body": ["list<$1> $2 = [SELECT $3 $0 FROM $1];"],
 "description": "SOQL query assignment to List variable"
},

}
Happy Learning!!!!

1 comment:

  1. https://marketplace.visualstudio.com/items?itemName=helpers.salesforce-code-snippets

    ReplyDelete