Tuesday, January 30, 2018

Using Chartjs in Lightning Components

ChartJS provides interactive and animated HTML 5 based javaScript charts. We can use these in Lightning components to display charts.

I have created a sample lightning app which display different charts by using salesforce data.

I am going to display opportunities amount(in millions) grouped by forecast category. First of all store the Chartjs file in static resource in order to use it in lightning components.

Download the Chartjs file which I am using from this link Chartjs download


You can download complete code along with static resource from below Github repository and deploy to your org.

Chartjs-in-Lightning-Sample-Code

Below is sample code used to display charts in above snapshot.


Hope this will help!!


Wednesday, January 24, 2018

How to use Lightning Icons (svg icons) in Visualforce Page

Salesforce provide different kind of Icons which can be used in Lightning component. As now we have an option to include slds in Visualforce pages, we can utilize predefined Icons in Visualforce page.

For complete list of icons please refer Lightning Icons

Icons have been divided in 5 different categories (Standart,Utility,Custom,Doctype and Action). In this blog we are going to explore how to utilize these icons in VF page.

First of all, you have to include SLDS in VF page by using <apex:slds/> tag as shown below:

<apex:page showHeader="false" standardStylesheets="false" sidebar="false" docType="html-5.0" >
<head>
  <apex:slds /> 
</head>

<body class="slds-scope">
<!--body content-->
</body>
</apex:page>

Now in order to refer any svg icon, use below code:

<span class="slds-icon_container slds-icon-custom-custom22 slds-icon-text-default" >
<svg aria-hidden="true" class="slds-icon ">
<use xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:href="/apexpages/slds/latest/assets/icons/custom-sprite/svg/symbols.svg#custom22">
</use>
</svg>
<span class="slds-assistive-text">Custom 22</span>
</span>

Now i will explain all css class options:
  • Icon background color(.slds-icon_container)  : This is used to provide background color to icon. By default, (.slds-icon_container) has a transparent background. In order to provide backgroud similar to specified in icons in SLDS, use .slds-icon-[cateory name]-[icon name] class. 
For example, for account icon, I need to provide background, then use .slds-icon-standard-account class.

<span class="slds-icon_container slds-icon-standard-account" >
<svg aria-hidden="true" class="slds-icon">
<use xmlns:xlink="http://www.w3.org/1999/xlink" 
xlink:href="/apexpages/slds/latest/assets/icons/standard-sprite/svg/symbols.svg#account">
</use>
</svg>
<span class="slds-assistive-text">Account</span>
</span>

  • Icon color(.slds-icon): By default, Icons color (.slds-icon) is white. Icon color can be changed by using below classes:
  1. .slds-icon-text-default: same as default text
  2. .slds-icon-text-warning: yellow
  3. .slds-icon-text-error: red
Note that doctype icons have specific colors that cannot be changed with the CSS property.
  • Icon size(.slds-icon): You can use below class to specify the icon size:
  1. Extra-small (.slds-icon--x-small): typically used for small alert icons, with no background color.
  2. Small (.slds-icon--small): 1.5rem×1.5rem (for icons with a background color).
  3. Medium (default - requires no additional class): 2rem×2rem.
  4. Large (.slds-icon--large): 3rem×3rem.
Below is sample VF page code which display different svg icons belonging to different categories.

VF Page snapshot:

Hope this will help!!

Monday, January 22, 2018

Salesforce 1 Events in Lightning Experience and Salesforce 1 app

Salesforce provide predefined events by which lightning components interact with Salesforce 1.You can utilize these events in Salesforce 1 app or in in lightning container(lightning experience).

I will be covering few important events along with sample code. So lets start:
  • force:showToast
This can be used to display some message on UI. For example, you are loading records from server side on your components, then you can display message saying "Records are loaded successfully" when operation completed. 

Yo can also control the duration for which this message will be displayed on screen. This can also be used to display error, warning or info message. You can control the appearance of toast message by using type attribute.

var toast= $A.get("event.force:showToast");
////checking if SF1 event exist or not. 
//these events exist in lightning experience and Salesforce 1 
if(toast){
toast.setParams({
"title":"Success",
"type":"warning",
"message" : "Retrieved Records Successfully.."
}
)};
toast.fire();

  • force:navigateToSObject
This event can be used to redirect user to record detail page by specifying the recordId.

var sObectEvent = $A.get("e.force:navigateToSObject");
sObectEvent.setParams({
"recordId": component.get("v.recordId")
});
sObectEvent.fire();

  • force:navigateToRelatedList
This will open related list of record( specify the parent record id for related list).

var relListEvent = $A.get("e.force:navigateToRelatedList");
//relatedListId- The API name of the related list to display, 
//such as “Contacts” or “Opportunities”
relListEvent.setParams({
"relatedListId": "Cases",
"parentRecordId": component.get("v.recordId")
});
relListEvent.fire();

  • force:editRecord
This will navigate to record edit page specified by recordId.

var sObectEditRecEvent = $A.get("e.force:force:editRecord");
sObectEditRecEvent.setParams({
"recordId": component.get("v.recordId") 
});
sObectEditRecEvent.fire();

  • force:refreshView
This event will refresh the complete UI. So if you perform any operation and then want reload the component, then you can utilize this event.

$A.get('e.force:refreshView').fire();

For further reference on other events and their usage please refer SF1 Events



Below is sample code utilizing SF1 events. This component displays list of account records and allow user to navigate to record detail page and edit page by using SF1 events.

Hope this will Help!!!


Monday, January 1, 2018

SHARING AND VISIBILITY DESIGNER : Exam preparation guide and tips

I had started planning for Salesforce Application Architect journey in Nov, 2017. As in order to achieve this, I need to passed below mention 2 exam as other required exams I had already cleared.
  • Certified Sharing and Visibility Designer
  • Certified Data Architecture and Management Designer
As Sharing and security is my favorite, so I start preparing for "Certified Sharing and Visibility Designer" exam. It took almost 1 month for preparation and finally I cleared first architect exam on 30 Dec, 2017.


Through this blog, I am going share my preparation experience and tips for everyone who all are planning for this.
  • For self study, please refer Resource Guide for Sharing and Security, which contains all the study material links for different topics. If you complete this, then you are ready for this exam. 
  • Please do practice on all topics related to declarative sharing and programmatic sharing.
This exam contains three sections:
  1. Declarative Sharing (68%)
  2. Programmatic Sharing(25%)
  3. Performance(8%)
Tips on different sections:

Declarative Sharing
  • Candidate must have complete understanding of different record sharing in built functionality like OWD, Role Hierarchy, Sharing Rules, Manual Sharing, Teams, Territories etc.
  • Custom permissions, Profiles and permission sets.
  • As I was not able to do practice on Territories, I just went through Salesforce help section for territories. Important topics are difference between Territory management(1.0) and Enterprise Territory Management (2.0) and their capabilities.
  • Must do practice on Account Teams and Opportunities. Different scenarios like who all can add team members, who can change record owner, what level of access can be given to user considering object OWD setting etc.
  • Permission required for creating list views and with whom all list view can be shared.
  • Custom settings, named Credentials and Custom metadata.
  • Ownership Skew, Lookup Skew and Account Skew and their impact on performance.
  • Always remember that manual sharing of record or manual sharing created through apex get deleted when record owner changes.
  • Differences between shield and classic encryption.
  • Record Access Grants(Implicit grant, Group membership grant, Inherited grant and explicit grant).
  • Reports and dashboard folder access and permission required to manage this. Also cover different types on file and folder access permissions.
  • Always remember that External default sharing level of object should be equal to or less restrictive than internal default sharing level.
  • Public groups (who all can be added and how access can be restricted to higher role using public groups).

Programmatic Sharing
  • How to force object permission and FLS in apex and VF page (using schema describe methods).
  • How to use apex manage sharing for standard objects and custom objects

Performance
  • Granular locking: Usually group membership get locked if any configuration happens. This will make impossible to perform group membership changes during this lock period.  If Granular locking feature is enabled then system will lock portion of records instead of locking entire Group maintenance table. This allow multiple update simultaneously if there is no hierarchical or other relationship between the roles and groups involved in the update.
  • Parallel Sharing rule calculation:  If Salesforce perform any activity (maintenance or upgrade)  then all sharing recalculation jobs get killed. In order to avoid this, consider enabling parallel Sharing Rule calculation. This will split the job in multiple threads which will run asynchronously. If Salesforce perform any activity, these jobs will not be killed and resume after salesforce activity.
  • Deferred Sharing Calculation : Best fit if you can buy out maintenance window from live user. Once you enable this, system will not perform any sharing calculation and you can perform major configuration changes like role changes, public group reassignment etc.
  • Avoid Account data skew, lookup skew and ownership data skew.
  • Avoid creating more nested public groups

You ran refer below mentioned my blogs links which explain things in summarized way:



Monday, December 25, 2017

Custom Permissions : Way to control user access to different functionality in Salesforce

Problem Statement

There is a very common scenario in which admin has to configure different validation rules, workflow rules which fires based on User Id or Profile Id.

Consider below mentioned scenarios:
  • Position (Custom Object) records can be closed by user belonging to specific profile.
  • You have created a VF page where you display specific section to users based on profile. 

In both scenarios, you have to check for profile Id in validation rule as well as in VF (to rendered specific section).





Now after some time if you have to enable the above mentioned functionality to new profile or to specific user then, you have to modify the validation rule as well as your VF page code.

Solution

You can use custom permission for these kind of scenarios.

Custom permission is just a record which can be referenced in validation rule, workflow rules, VF, Apex etc. You can assign custom permission to profile or permission set (similar way in which we assign VF page and Apex class).

Now you can check custom permission in validation rules and VF by using global $Permission variable.

Steps to use custom permission and use as per above scenario:
  • Create custom permission (Navigate to Set Up--> Develop--> Custom Permissions).
  • Create new custom permission.

  • Add custom permission to profile or permission set(navigate to Enable custom permission section).

  • Modify the validation rule to and VF to refer custom permission instead of profile id.



So custom permission help us to control different functionality in salesforce to different users. If you have to enable functionality for single user then add custom permission to permission set and then add that permission set to user.

Alternate Approach

All admins/developers were using custom setting to control functionality for different users but after launch of custom permission, jobs of developer or admin will be easy.

Custom Permission in Apex

You can use below static method to find out list of user who have permission for custom permission:


public static List<User> findUsersWithCustomPermission(String customPermissionname)
{
    List<user> userList = new List<User>();
Set<Id> permissionSetIds = new Set<Id>();
    for (SetupEntityAccess access : [ SELECT ParentId FROM SetupEntityAccess 
WHERE SetupEntityId IN ( SELECT Id FROM CustomPermission 
            WHERE DeveloperName = :name)]) {
        permissionSetIds.add(access.ParentId);
    }
if(permissionSetIds.size()>0){
userList = [SELECT Username FROM User 
WHERE Id IN (SELECT AssigneeId FROM PermissionSetAssignment
WHERE PermissionSetId IN :permissionSetIds)];
}
    return userList;
}

Hope this will help!!!

Saturday, December 16, 2017

Insufficient Privileges : How to troubleshoot record access issue in Salesforce

"Insufficient Privileges" is common error which appears on user interface if user tries to access/edit a record. As we know that apart from OWD and profile, record can be shared by using sharing rules, role hierarchy, manual sharing or apex sharing.



If some user report this kind of issue, then instead of checking all sharing options, we can directly run below query to check what kind of access that user have for given record.

SELECT RecordId, HasReadAccess, HasTransferAccess, MaxAccessLevel, HasAllAccess, HasDeleteAccess, HasEditAccess FROM UserRecordAccess  WHERE UserId = “005xxxxxxxxx”AND RecordId = “001xxxxxxxx”

Where 005xxxxxxxxx is user id and  001xxxxxxxx is record Id.

HasAllAccess Indicates whether a user has all access–read, edit, delete, and transfer—to the record (true) or not (false).
HasReadAccess, HasEditAccess , HasDeleteAccess ,HasTransferAccess return Boolean value.
MaxAccessLevel return access level like None, read, Edit,Delete,Transfer and All.


This query will help to understand whether user has access to record or not. After that you can check different options (sharing rules, role, apex sharing etc.) to find out why that user is not having access to record.

Hope this will help!!!

Tuesday, December 12, 2017

Formatting and Localizing dates in javascript in Lightning

Date formatting in javascript

AuraLocalizationService JavaScript API provides methods for localizing dates and formatting.

Use the formatDate() to format date by providing format string as second argument.

formatDate (String | Number | Date date, String formatString)

Use $A.localizationService to use the methods in AuraLocalizationService.

Below are few examples of format string and their output:

var now = new Date();
var dateString = "2017-12-12";

// Returns date in the format "Dec 12, 2017"
console.log($A.localizationService.formatDate(dateString));

// Returns date in the format "2017 12 12"
console.log($A.localizationService.formatDate(dateString, "YYYY MM DD"));

// Returns date in the format "December 12 2017, 11:03:47 PM"
console.log($A.localizationService.formatDate(now, "MMMM DD YYYY, hh:mm:ss a"));

// Returns date in the format "Dec 12 2017, 11:03:57 PM"
console.log($A.localizationService.formatDate(now, "MMM DD YYYY, hh:mm:ss a"));

Refer below link for more details:
tokens supported in format string

Localization

Lightning framework provides client-side localization support on input/output elements. This helps in customize the date and time format.

For example, below code will display date in Europe/Berlin timezone (Dec 13, 2017 2:17:08 AM)

<aura:component>
    <ui:outputDateTime value="2017-12-13T02:17:08.997Z"  timezone="Europe/Berlin" />
</aura:component>

To customize date and time format use, lightning:formattedDateTime.

The attributes on lightning:formattedDateTime helps you to control formatting at a granular level. For example, you need to display the date using the MM/DD/YYYY format, then use below code:

<lightning:formattedDateTime value="{!v.datetimeValue}" timeZone="Europe/Berlin" year="numeric" month="numeric" day="numeric"/>


datetimeValue can be set in controller code either in doInit or any other function as mentioned below:

var date = new Date();
component.set("v.datetimeValue", date)

Locale Information on client side controller

  • $A.get("$Locale.timezone")  : This will return timezone like Europe/Paris, Europe/Berlin etc.
  • $A.get("$Locale.currency") : This will return org currency locale like "$", "¥" etc.

Hope this will help!!!!