Saturday, August 17, 2019

LWC: Modularizing Code using Singleton pattern


Imagine that we have a custom LWC component, which we drag-and-drop onto a Lightning page in Lightning App Builder. This component has 2 design attributes for First Name and Last Name. We need a way to access these values from any component without communicating down the containment hierarchy. Setting the public properties of child components becomes a tedious job if there are nested components.

To solve this issue, we can use the Singleton Pattern, which states that the number of instances of an object must be restricted to one only, hence the "single" in Singleton. The intent of the Singleton is ensuring a class has only one instance, and providing a global point of access to it.

For the sake of simplicity, I have created 2 components component1 and component2 where component2 is the child of component1. I need to access the design attribute values of the parent component from the child component. In this example, we are storing the design attribute values in a single central place, sharedData component, written in the Singleton pattern.

which can be accessed by any component in the application like below:

Similarly, to get one point of access to custom labels, I have created a component customLabels using Javascript classes to access the custom labels

To know more about Object.freeze(), refer one of my post titled Javascript: Preventing Object Modification. Now any component in the application can access these values like below:


Please see the below repo for the code:
https://github.com/iamsonal/lwc-singleton

Share This:    Facebook Twitter

Saturday, August 10, 2019

LWC: Modal implementation



Check the code in the below repo for the modal implementation in LWC:
https://github.com/iamsonal/lwc-modal

Notes:
  • If you want to hide the close icon, then set the hide-close property to true like below:

  • <!-- modalContainer.html -->
    <template>
        <c-modal name="Modal Name" title="Modal Title" hide-close>
        </c-modal>
    </template>

  • Similarly, if you want to display a large modal, then set the is-large property to true like below:

  • <!-- modalContainer.html -->
    <template>
        <c-modal name="Modal Name" title="Modal Title" hide-close is-large>
        </c-modal>
    </template>


  • Using slots (unnamed and named), we are passing the modal body and footer content from parent into the child component like below. In this way, we can control the markup that can be displayed in the modal. For more information about how to use slots, check the LWC documentation.

  • <c-modal name="Modal Name" title="Modal Title" >
    
        <!-- Unnamed Slot -->
        <p>This is some content</p>
    
        <!-- Named Slot -->
        <div slot="footer" style="display: inline;">
            <lightning-button label="Close" variant="neutral" onclick={handleCancelModal}></lightning-button>
        </div>
        
    </c-modal>


  • Set the style-class property to apply a custom CSS in the modal.

Share This:    Facebook Twitter

Saturday, July 13, 2019

LWC: Override CSS of standard Lightning Web Components

Recently, I got a requirement where I had to override the CSS of lightning-card component, specifically to change the background colour of the header of the card component.

Shadow Dom have their own little kingdom and cannot be styled from outside, except if they would provide some options to do so. Currently, it's not possible to style standard Lightning Web Components;

I am providing a hacky workaround to get the desired results. I added the below code in my helloExpressions component:
renderedCallback() {
    const style = document.createElement('style');
    style.innerText = `c-hello-expressions .slds-card__header {
    background-color: #54C2B2;
    }`;
    this.template.querySelector('lightning-card').appendChild(style);
}

and this is how it looks:

UPDATE:
It seems there is a cleaner approach as suggested by pdebaty: loading CSS using loadStyle...lol. You can go through the StackExchange article to understand more in details.


Share This:    Facebook Twitter

Saturday, June 1, 2019

LWC: Retrieving custom labels dynamically


To access labels in a Lightning web component, import them from the @salesforce/label scoped module.
import greeting from '@salesforce/label/c.greeting';
import salesforceLogoDescription from '@salesforce/label/c.salesforceLogoDescription';

As far as the official documentation goes, it is clear that one needs to know the name of a custom label at design time; it is impossible to evaluate the value at runtime by knowing their name.

Arteezy and Sfdcfox commented in this StackExchange post that you can use Salesforce inspector and tooling API to retrieve the custom labels using this query:
SELECT Id, Name, Value FROM CustomLabel

Based on this, I have created an LWC service component customLabelService, which will retrieve all the custom labels and store it as an object on client-side. You can use this component as below:


NOTES:
1. As per this StackExchange post, there is no way of getting a valid API-capable sessionId from a Lightning component because sessions obtained from Apex used by a Lightning component are not API enabled. That's why as a workaround, I have created a VF page, and getSessionIdFromVFPage method in CustomLabelController class to retrieve the sessionId. You can also refer to this post to know more in details.

2. If there is a requirement where you need to retrieve all the labels with a known prefix, then change the resourcePath (URI) to below:
/services/data/v46.0/tooling/query/?q=Select+id,Name,Value+from+CustomLabel+WHERE+Name+LIKE+'OAuthModal%25'

where the prefix is OAuthModal. I checked in Workbench, and this works fine, but you will need to tweak the code to pass the prefix.

3. As per this StackExchange post, there are two objects that represent labels, CustomLabel and ExternalString. So you can also use tooling API to fetch the labels from ExternalString using the below query:
SELECT Id, Name, Value, Language FROM ExternalString


UPDATE: 
Please refer the code of this project from the link below:
https://github.com/iamsonal/Custom-Labels

Share This:    Facebook Twitter

Saturday, March 9, 2019

Javascript: Array Helper Methods

forEach()

forEach() is usually used as a replacement for traditional for-loop. Lets add an array of numbers. In classic Javascript, this is how you will write the code:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

for (var i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(sum);

Using forEach helper method, the code will be something like below:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

numbers.forEach(function(number) {
  sum += number;
});

console.log(sum);

The iterator function doesn't have to be an anonymous function. We can declare a function separately and then pass it in forEach as below:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

function addNumbers(number) {
  sum += number;
}

numbers.forEach(addNumbers);

console.log(sum);

map()

Write a loop that iterates over a list of numbers, doubles the value of each number in the array and then pushes the doubled number into a new array.

In classic JS, this is how the code will look like:
var numbers = [11, 12, 13, 14, 15];

var double = [];

for (var i = 0; i < numbers.length; i++) {
  double.push(numbers[i] * 2);
}

console.log(double);

Now we will refactor the code above to use the map helper.
var numbers = [11, 12, 13, 14, 15];

var double = numbers.map(function(number) {
  return number * 2;
});

console.log(double);

You can also reformat the code like below:
var numbers = [11, 12, 13, 14, 15];

var doubleFn = (num) => num * 2;

var double = numbers.map(doubleFn);

console.log(double);

One of the most common uses of map is collecting properties of an array of object. Check the code below:
const persons = [
  {firstName:"John", lastName:"Doe"},
  {firstName:"Mike", lastName:"Crusoe"},
];

const firstNames = persons.map(person => person.firstName);

console.log(firstNames);

filter()

We will be filtering out persons who are working in Finance department. This is how we will write code in classic Javascript:
var persons = [
  {firstName:"John", lastName:"Doe", age:46, department:"Finance"},
  {firstName:"Mike", lastName:"Crusoe", age:40, department:"Finance"},
  {firstName:"Mary", lastName:"Jane", age:30, department:"HR"}
];

var filteredPersons = [];

for (var i = 0; i < persons.length; i++) {
  if (persons[i].department === "Finance") {
    filtered.push(persons[i]);
  }
}
console.log(filteredPersons);

Now we will refactor the code above to use the filter helper.
const persons = [
    { firstName: "John", lastName: "Doe", age: 46, department: "Finance" },
    { firstName: "Mike", lastName: "Crusoe", age: 40, department: "Finance" },
    { firstName: "Mary", lastName: "Jane", age: 30, department: "HR" }
];

const filteredPersons = persons.filter(person => person.department === 'Finance');

console.log(filteredPersons);

find()

This method will return only first element where callback function returns true; it don't process other elements.

We will search for user whose name is Mike. This is how we will write code in classic Javascript:
var users = [
  {name:"John"},
  {name:"Mike"},
  {name:"Mary"}
];

var user;

for (var i = 0; i < users.length; i++) {
  if (users[i].name === 'Mike') {
    user = users[i];
    break;
  }
}

console.log(user);

Now we will refactor the code above to use the find helper.
const users = [
  {name:"John"},
  {name:"Mike"},
  {name:"Mary"}
];

const user = users.find(user => user.name === 'Mike');

console.log(user);

Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top