Category Archives: Salesforce

How to create a report that shows user license?

To display Salesforce as a User License type on report, Below is the workaround:

  • Create a Custom Formula Text field under the User object:
    1. Go to Setup | Customize | Users | Fields
    2. Click on New and select “Formula” field type and then “Text”
    3. Use “Profile.UserLicense.Name” in the formula editor
    4. Click on Save
  • Create a New Administrative User report:
    1. Go to the Report tab
    2. Click on New report
    3. Under the Administrative reports | Select Users
    4. Add the New Custom Formula field in the report
    5. Run the Report and Save

SOQL Query To Get Users with Salesforce User License

Get all Users with User License:

List<User> userList = [Select Id, Name, Profile.UserLicense.Name From User];

Get Users with specific User License:

List<User> userList = [Select Id, Name, Profile.UserLicense.Name From User WHERE Profile.UserLicense.Name = 'Salesforce'];

Display Toast Message in Lighting Component

Using force:showToast we can display a toast notification with a message. A toast displays a message below the header at the top of a view. The message is specified by the message attribute.

Attributes:

  • title Specifies the toast title in bold.
  • message Specifies the message to display. It is a required attribute.
  • messageTemplate Overwrites message string with the specified message. Requires messageTemplateData.
  • messageTemplateData An array of text and actions to be used in messageTemplate.
  • key String Specifies an icon when the toast type is other. Icon keys are available at the Lightning Design System Resources page.
  • duration Toast duration in milliseconds. The default is 5000ms.
  • type The toast type, which can be error, warning, success, or info. The default is other, which is styled like an info toast and doesn’t display an icon, unless specified by the key attribute.
  • mode The toast mode, which controls how users can dismiss the toast. The default is dismissible, which displays the close button.
    dismissible: Remains visible until you press the close button or duration has elapsed, whichever comes first.
    pester: Remains visible until duration has elapsed. No close button is displayed.
    sticky: Remains visible until you press the close buttons.

Example:

Component:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
    <div>
        <lightning:button label="Information"
                          variant="brand"
                          onclick="{!c.showInfo}"/>
        <lightning:button label="Error"
                          variant="destructive"
                          onclick="{!c.showError}"/>
        <lightning:button label="Warning"
                          variant="neutral"
                          onclick="{!c.showWarning}"/>
        <lightning:button label="Success"
                          variant="success"
                          onclick="{!c.showSuccess}"/>
    </div> 
</aura:component>

Component JS Controller:

({
    showInfo : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Info',
            message: 'This is an information message.',
            duration:' 5000',
            key: 'info_alt',
            type: 'info',
            mode: 'dismissible'
        });
        toastEvent.fire();
    },
    showSuccess : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Success',
            message: 'This is a success message',
            duration:' 5000',
            key: 'info_alt',
            type: 'success',
            mode: 'pester'
        });
        toastEvent.fire();
    },
    showError : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Error',
            message:'This is an error message',
            duration:' 5000',
            key: 'info_alt',
            type: 'error',
            mode: 'pester'
        });
        toastEvent.fire();
    },
    showWarning : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Warning',
            message: 'This is a warning message.',
            duration:' 5000',
            key: 'info_alt',
            type: 'warning',
            mode: 'sticky'
        });
        toastEvent.fire();
    }
})

Output:

Salesforce Lightning Data Service

Salesforce introduced Lightning Data Service(LDS) in Winter 17, It is to serve as the data layer for Lightning. It is similar like Standard Controllers in Visualforce Page.

Advantages of Lightning Data Service:

  • Lightning Data Service allows to load, create, edit, or delete a record without requiring Apex code and SOQL query.
  • Lightning Data Service handles sharing rules and field-level security.
  • Records loaded in Lightning Data Service are cashed and shared across all components.
  • When one component updates a record, the other component using it are notified.
  • Lightning Data Service supports offline in Salesforce1.

Consideration of Lightning Data Service:

  • Lightning Data Service is only available in Lightning Experience and Salesforce1.
  • Lightning Data Service does not support bulk operations.
  • Lightning Data Service in other containers, such as Lightning Components for Visualforce, Lightning Out, or Communities isn’t supported.
  • Lightning Data Service notifies listeners about data changes only if the changed fields are the same as in the listener’s fields or layout.

We can use force:recordData Lightning component to declare Lightning Data Service. To use Lightning Data Service, we need specify the following attributes:

  • recordId specifies the record to load. Records can’t be loaded without a recordId.
  • mode can be set to either EDIT or VIEW, which determines the behavior of notifications and what operations are available to perform with the record. If you’re using force:recordData to change the record in any way, set the mode to EDIT.
  • layoutType specifies the layout (FULL or COMPACT) that is used to display the record.
  • fields specifies which fields in the record to query. The fields or layoutType attribute (or both) must be provided.
  • target* attributes starting with target indicates values to be returned from Data Service. It can return record or error.
  • recordUpdated edit mode does not updates record by default, to update target* attributes, use this method handler.
  • targetRecord will contain only the fields relevant to the requested layoutType and/or fields atributes.
  • targetFields is populated with the simplified view of the loaded record.
  • targetError is to the localized error message if the record can’t be provided.

Here is an example of Lightning Data Service: In below example I’ve created a Lightning Quick Action to edit Contact Email and Phone using Lightning Data Service force:recordData.

ContactEditDataService.cmp :

<!--ContactEditDataService.cmp-->
<aura:component implements="force:appHostable,force:lightningQuickActionWithoutHeader,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <!--Declare Atrribute-->
    <aura:attribute name="contact" type="Object"/>
    <aura:attribute name="contactRecord" type="Object"/>
    <aura:attribute name="recordSaveError" type="String"/>
    
    <force:recordData aura:id="conRec" 
                      layoutType="FULL" 
                      recordId="{!v.recordId}"  
                      targetError="{!v.recordSaveError}"
                      targetRecord="{!v.contact}"
                      targetFields="{!v.contactRecord}"
                      mode="EDIT"
                      recordUpdated="{!c.handaleRecordUpdated}"/>
    
    <div class="slds-box"> 
        <div class="slds-text-heading_medium">
            {!v.contactRecord.Name}
        </div> 
        
        <aura:if isTrue="{!not(empty(v.recordSaveError))}">
            <br />
            <div class="error slds-box">
                {!v.recordSaveError}
            </div> 
        </aura:if>
        
        <div class="slds-form--stacked slds-tile"> 
            <div class="slds-form-element">
                <label class="slds-form-element__label">Phone: </label>
                <div class="slds-form-element__control">
                    <lightning:input type="tel" value="{!v.contactRecord.Phone}" name="phone" required="true"/>
                </div>
            </div>
            <div class="slds-form-element">
                <label class="slds-form-element__label">Email: </label>
                <div class="slds-form-element__control">
                    <lightning:input type="email" aura:id="email" value="{!v.contactRecord.Email}" required="true"/>
                </div>
            </div>
            <div class="slds-form-element">
                <lightning:button variant="brand" title="Save" label="Save" onclick="{!c.handleSaveContact}"/>
                <lightning:button title="Cancel" label="Cancel" onclick="{!c.handaleCancel}"/>
            </div>
        </div>
    </div>
</aura:component>

ContactEditDataService JS Controller :

({
    handleSaveContact : function(component, event, helper) {
        helper.saveContact(component, event, helper);
    },
    
    handaleRecordUpdated : function(component, event, helper) {
        helper.recordUpdated(component, event, helper);
    },
    
    handaleCancel : function(component, event, helper) {
        $A.get("e.force:closeQuickAction").fire();
    }
})

ContactEditDataService Helper :

({
    //Save contact record
    saveContact : function(component, event, helper) {
        component.find("conRec").saveRecord($A.getCallback(function(saveResult) {
            if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
                //To close the component with success message
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Success!",
                    "message": "The record has been updated successfully."
                });
                toastEvent.fire();
                $A.get("e.force:closeQuickAction").fire();
                $A.get('e.force:refreshView').fire();
            } else if (saveResult.state === "INCOMPLETE") {
                //Show data saved incomplete message
                component.set("v.recordSaveError","Data saved incomplete.");
            } else if (saveResult.state === "ERROR") {
                //Show error message
                var errMsg = "";
                for (var i = 0; i < saveResult.error.length; i++) {
                    errMsg += saveResult.error[i].message + "\n";
                }
                component.set("v.recordSaveError", errMsg);
            } 
        }));
    },
    
    //Refresh record after update
    recordUpdated : function(component, event, helper){
        var changeType = event.getParams().changeType;
        if (changeType === "CHANGED") {
            component.find("conRec").reloadRecord();
        }
    }
})

Output: