How To Enable SObject Intellisense in VSCode for Salesforce DX

Quick Tip.

Salesforce DX already comes with Intellisense for Apex classes and the different primitive types. Eg. Strings

For SObjects it’s a per-project setting you need to enable once you have your project created. Open the Command Palette and choose SFDX: Refresh SObject Definitions

What the command does under the hood is it will create a class definition of the SObject and store them under the .sfdx folder/tools folder. These don’t get committed to version control as the .sfdx folder is by default ignored.

Each class has properties that allows the Intellisense to work.

Once enabled you are good to go.

If you want more tips and information on Salesforce DX checkout my youtube playlist where I cover them in detail.

How To Get Started With Org Development Model With Salesforce DX

There are two development models you can follow with Salesforce DX.

First is the package model where you develop against a scratch org and prepare all the components that are needed to deploy, similar to change sets but smarter as it handles the dependencies for you. We will talk about this more in the future.

The other method is what you would be most familiar with if you have been developing with Salesforce for sometime now(Force.com IDE/Mavensmate/IntelliJ), you develop changes against a sandbox and move the metadata to deploy to the target org till you deploy to production.

With Salesforce DX you can still continue to develop against a sandbox. You do not need to enable Dev Hub for developing against a sandbox or DE org.

Requirements ofcourse if you should have VSCode installed, the VSCode Salesfor ce Extension Pack and the Salesforce CLI.

Boot up VSCode and Open the Command Prompt and type SFDX : Create Project with Manifest

The scaffolding created will contain a manifest folder with a package.xml

The default package.xml adds the base ApexClass, ApexComponent, ApexPage, ApexTestSuite, ApexTrigger,AuraDefinitionBundle and StaticResource.

Next is to Authorise the Sandbox you want to work on, Go to the command pallete. SFDX: Authorize and Org.

Next right click on the package.xml and choose Retrieve Source in Manifest in Org.

Once done you can start modifying your code. Right click on a file to deploy it to the Source Org or enable the auto deploy on Save settings.

That’s it, you should now be able to work with your existing sandbox.

Check out my video and subscribe if you want more tips and suggestions.

Fix for flowruntime:lookup Error With Salesforce Flows

If you recently used the custom lookup component while working on Salesforce Flows and get this error.

We can’t display component ‘flowruntime:lookup’, because it isn’t supported in Classic runtime. 

Chances are you still are on Classic. The component only works on Lightning. An easy fix is to enable the Lightning runtime in Flows.

  1. From Setup, enter Process Automation Settings in the Quick Find box, then select Process Automation Settings.
  2. Select Enable Lightning runtime for Flows.
  3. Save your changes.

How to Clean Up The List of Orgs on force:org:list on Salesforce DX

If you run the cli command sfdx force:org:list and see a bunch of old orgs you recently authorized or scratch orgs that you no longer use.

You can easily clean them up by logging off from the org.

sfdx force:auth:logout -u <alias>

You get this confirmation screen and important reminder if you want to reuse your scratch org you must know the pasword before logging out.

If you don’t need the scratch org you can delete them with the command below.

sfdx force:org:delete -u <alias>

Enable Auto Push or Auto Deploy With Salesforce DX on VSCode

The title says it all if you have been developing before on Force.com IDE/ Mavenmate/IntelliJ and started using Salesforce DX. One that gets pretty tedious fast is manually pushing your code to your scratch org or deploying to your non-tracked org(DE/Sandbox).

To enable auto push/deploy simply edit the .vscode/settings.json. This folder can be hidden on Windows or Mac. On a Mac open the Finder and hit CMD+Shift dot(.) to display hidden files.

Add the following settings and set it to true.

"salesforcedx-vscode-core.push-or-deploy-on-save.enabled": true

My settings.json looks like below.

Another method to do this same steps is to go to the Code menu and choose Preferences then Settings.

Next click on Workspace tab then search for Salesforce

Under Salesforce Feature Previews(3rd one), tick the box under Salesforcedx-vscode-core › Push-or-deploy-on-save: Enabled

This is particularly useful specially for cloned repository where the .vscode folder is not part of the repository.

Don’t forget to update the .gitignore file if you are using version control and add the .vscode folder.

Happy coding!

Creating a Modal Popup Lightning Component

A quick tutorial on how to create a modal popup with Lightning Component.

What is modal popup?

Modal popup acts like a container for your content that displays on top of the content you are viewing. Imagine content stacked on top of it.

In short, a modal popup is a very handy way of showing content in front of your app.

How to build one in lightning?

  • First create lightning component and add a boolean attribute then default it’s value to false
  • On your controller, toggle the boolean value as you see fit based on events.
    • cancelBtn onclick event sets the displayModal value to true, thus displaying the modal.
    • yesBtn onclick event tied to the button navigates to another URL and sets the displayModal value back to false, thus hiding the modal popup

That’s it, you should have a working modal popup ready to go.

Final code is available here in GitHub

https://github.com/olopsman/lc-modal-popup

How to Validate forms built with Lightning Components

Learn how to validate lightning components forms easily.

I recently had a requirement to create a basic lightning component to capture form inputs. I previously had a not so good experience with building custom validation with Lightning components back in Summer17 when lightning was pretty new. I was using force:inputField and also used lightning:inputField.

Past few years it has become more efficient and easier with just the lightning:input field and default HTML5 APIs.

I have a simple bank form that captures and validates the form as such and when submitted validates the required fields.

Form

For the Bank Account Name input field specify the required attribute as true and check the validity of the field.

I use reportValidity to display the error message in the input field

And for the Bank Account Number input field aside from setting the field as true, I also specified a regular expression pattern. And then used the setCustomValidity function to display a custom error message.

And that folks, is how easy to validate the input form. Hit the comments below if you need help building your validation.

Recommended Books:

How To Use Regular Expressions (Regex)

“Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.” – Jamie Zawinski

Every now and then I have some requirements where it entails parsing some data where I need to use some form of Regular Expression(regex), it is a syntax to use to search for patterns in a string or sets of strings. At first, the syntax looks intimidating and most people would shy away and resort to writing some functions to solve the issue.

Learning regex is a must-have skill to have as it can be applied to a wide range of tasks that needs some sort of search or parsing and is widely available in most programming languages, works on shells, text editors and IDEs, etc..). I use it most of the time when writing front end Javascript validation and backend logic in Apex NodeJS, Java/Groovy , Swift and Python

I created this cheat sheet that covers the basics and some handy tips.

Flags

The search pattern is normally delimited by two slash characters /abc/. At the end we can specify a combination of the following flags.

  • g (global) – Don’t return after the first match
  • m (multi-line) – ^ and $ match start/end of line
  • i (insensitive) case insensitive match
  • x (extended) ignore whitespace
  • X (eXtra) disallow meaningless escape
  • s (single line) dot matches new line
  • u (unicode) match with full unicode
  • U (Ungreedy) make quantifiers lazy
  • A (Anchored) anchor to start of pattern
  • J (Jchanged) allow duplicate subpattern names
  • D (Dollar end only) $ matches only end pattern


Anchors

[ninja_tables id=”2853″]

Quantifiers

[ninja_tables id=”2854″]

Or and Brackets

[ninja_tables id=”2857″]

When inside bracket expressions all special character rules do not apply. E.g. \ to escape a character does not apply

Character Classes

[ninja_tables id=”2861″]

In order to be taken literally, you must escape the characters ^.[$()|*+?{\with a backslash \ as they have special meaning.

Groupings

[ninja_tables id=”2862″]

Greedy and Lazy Quantifiers

The quantifiers ( * + {}) are greedy operators, so they expand the match as far as they can through the provided text.

[ninja_tables id=”2868″]

Boundaries

[ninja_tables id=”2880″]

Back References – \1

[ninja_tables id=”2883″]

Look-ahead and Look-behind

[ninja_tables id=”2885″]

Top Regular Expressions

[ninja_tables id=”2884″]

Summary

As we’ve learned regex is so powerful and its’s application is wide. Listed below some of few things you can do with regex within your project.

  • input and data validation –
    • validate user input in forms
    • validate data before applying logic or saving to database
    • validating JSON schema
  • replacing values – replace specific data in a string
  • text parsing – eg. retrieve only bits of data from a string or URL or delimiters
  • string replacement – eg on some IDE you can find and replace a string, use regex to search for particular patterns
  • web scraping – look for specific patterns for data to scrape

Sample Codes

Apex class that implements removal of white space not found in quotes

Python script that crawls pages that matches the pattern.

And finally, as a takeaway just learn the syntax and hack away.

How to Create a Generic Class for Mocking REST Callouts for Unit Test

I’m starting a new habit of posting regularly on my blog every week. I’ll be kicking it off with tips for creating a generic class or a mocking factory for mocking calls to an external third-party service.

Why do we need to do a mock?

When running unit tests the platform does not allow to do a callout to external dependencies. To test our code base we would need to mock the response as if calling the third party dependency.

By mocking we focus on the code being tested, isolating it from the state and behavior of the external system. The dependencies are simulated and the output state can be controlled.

To start we create a class that implements the HttpCalloutMock. This class enables sending a fake response when doing HTTP callouts. When our code makes a callout, the response will come from our HttpCalloutMock class.

When creating the class we define the constructor and parameters. We can make it generic and serve as a mock factory. Instead of writing several mock classes for every type of response, we only write it once which promotes code reusability best practices. And during unit testing, we define the mock response on the fly.

Here is our sample class which implements the HttpCalloutMock.

And if we have a class that does an HTTP Callout and we want to write a unit test for it. This is how it going to look like.

This is how we would create a unit test.

Key Takeaways

  • Use named credentials when possible when doing HTTP Callouts. Will talk about this more in the future.
  • When writing the unit test, the key is to call Test.setMock() which makes sure any callout from your code will return the Mock object.
  • Define the mock response on the fly to test different response.

Hope you find this useful. Stay tuned for more coding content and tips. If interested in the source code it is available in GitHub.

Custom Lightning Component Related List With Real-Time REST Data

How to build a custom lightning component related list with real-time REST data. For this tutorial, I’ll show a technique on how to integrate external data and display the data real-time as a related list in Salesforce. This would not use an external object but a simple custom related list component that uses lightning:datatable base component and a controller than retrieves data via callout to an external REST resource and display them in Salesforce.

This is how it would look like.

 

For this, I’m calling this a static REST resource that returns the following JSON response.

Next, we need to display this data in a related list in Salesforce. We create a simple lightning component that we can add using Lightning App builder.

Start with the following lightning component markup.

And controller that calls a helper.

The helper creates a server-side call that creates the REST callout. Then on the successful response, I’m setting the value for the mycolumns attribute by assigning a Javascript object assigning the properties of the column for the datatable. Then I simply assign the mydata attribute assigning and using JSON.parse to turn the response to a Javascript object. With that simple code, I have a related list.

Note: you do not need the var actions as this is for another method I’m working on.

Then for my controller, I have this simple call to my server

Then I simply drop the component on Lightning App Builder to the related list section for a quick UI match. That should be it.

Recommended Books: