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

Friday, March 8, 2019

Javascript: Arrow functions and this

Arrow functions are anonymous; there are only arrow function expressions. You can assign arrow function expression to a variable, can be used in an IIFE as well as a callback function. Below you will find valid arrow functions:

(a, b) => a + b // implicitly returning a + b

(a, b) => {                // explicitly returning a + b
   return a + b;
}

a => a * a                // omit () when there is one parameter

() => 2                   // () mandatory when there are no parameters

(a, b) => {               // explicitly returning JS object
   return {
      a1: a, b1: b
   }
}

(a, b) => ({              // implicitly returning JS object
   a1: a, b1: b
})

An arrow function does not have its own this. this in arrow functions is always statically defined by the surrounding lexical scope.
In the example below, when using traditional function, this refers to the num object, whereas when using arrow notation, this is pointing to the global object. Arrow functions doesn't have its own this, and so this refers to outer scope, and outer scope for num object is the window object.


Even if I use call() method, result is the same.


In the below example, when using traditional function, this refers to the global object, whereas using arrow function, we get the desired result.


In order to get the greeting message using the traditional function, there are several ways to keep reference to this object inside of setTimeOut function. You can create a self variable like below:

const str = {
    value: 'Delayed greeting',
    greet: function() {
        const self = this;
        setTimeout(function() {
            console.log(self.value);
        }, 2000)
    }
};

str.greet();

or bind with this like below:

const str = {
    value: "Delayed greeting",
    greet: function() {
        setTimeout(
            function() {
                console.log(this.value);
            }.bind(this),
            2000
        );
    }
};

str.greet();

It is not possible to use arrow function expression as a function constructor and create new objects from it.
Share This:    Facebook Twitter

Monday, March 4, 2019

LWC: Fetch picklist values

<!-- fetchPicklistValues.html -->
<template>
    <lightning-card title="WireGetPicklistValues" icon-name="custom:custom67">
        <template if:true={picklistValues.data}>
            <div class="slds-m-around_medium">
                <template for:each={picklistValues.data.values} for:item="item">
                    <lightning-input
                        key={item.value}
                        label={item.label}
                        data-value={item.value}
                        type="checkbox"
                        onchange={handleCheckboxChange}
                    ></lightning-input>
                </template>
            </div>
        </template>
    </lightning-card>
</template>


// fetchPicklistValues.js
import { LightningElement, wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import TYPE_FIELD from '@salesforce/schema/Account.Type';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class FetchPicklistValues extends LightningElement {

    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    @wire(getPicklistValues, {
        recordTypeId: '$objectInfo.data.defaultRecordTypeId',
        fieldApiName: TYPE_FIELD
    })
    picklistValues;

    handleCheckboxChange(event) {
        console.log(event.target.dataset.value);
        console.log(event.target.checked);
    }
}

As per documentation, use getPicklistValues wire adapter (from lightning/uiObjectInfoApi module) to fetch picklist values for a specified field.

Parameters:

  • recordTypeId—(Required) The ID of the record type. Use the Object Info defaultRecordTypeId property, which is returned from getObjectInfo or getRecordUi.
  • fieldApiName—(Required) The API name of the picklist field on a supported object.
  • propertyOrFunction—A private property or function that receives the stream of data from the wire service. If a property is decorated with @wire, the results are returned to the property’s data property or error property. If a function is decorated with  @wire, the results are returned in an object with a data property and an error property.
Find out more about the data inside objectInfo and picklistValues variable:


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